<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
      crossorigin="anonymous"
    />
    <!-- <link rel="stylesheet" href="../styles/main.css" /> -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="../styles/orderDashboard.css" />
    <link rel="shortcut icon" href="../icon.png" type="image/x-icon">
    <title>Invoice Dashboard</title>
  </head>
  <body>
    <%
      function formatRupiah(number) {
        return number.toLocaleString('id-ID', { style: 'currency', currency: 'IDR' });
      }
    %>
    <!-- Header -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark py-3">
      <button class="navbar-toggler ms-3" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto px-3">
          <li class="nav-item active">
            <a href="/invoiceDashboard" class="nav-link">Invoices</a>
          </li>
          <li class="nav-item">
            <a href="/invoiceDashboard/products" class="nav-link">Products</a>
          </li>
          <li class="nav-item">
            <a href="/invoiceDashboard/hampers" class="nav-link">Hampers</a>
          </li>
          <li class="nav-item">
            <a href="/invoiceDashboard/customers" class="nav-link">Customers</a>
          </li>
          <li class="nav-item">
            <a href="/invoiceDashboard/statistics" class="nav-link">Statistics</a>
          </li>
        </ul>
      </div>
      <div class="logout-container d-flex flex-row">
        <p class="text-light m-0 me-3 align-middle py-2">Invoice Account </p>
        <button class="btn btn-light me-3" onclick="redirect('/logout')">Logout</button>
      </div>
      
    </nav>

    <!-- Title -->
    <h1 class="w-100 text-center mt-5 mb-4">Invoice DashboardðŸ§¾</h1>

    <!-- Add Invoice Button Container -->
    <div class="container mt-4 d-flex justify-content-center ">
      <button class="btn btn-primary text-center px-5 me-2" onclick="redirect('/invoiceDashboard/addInvoice')">Add Invoice</button>
    </div>

    <!-- Invoice Container -->
    <div class="container mt-2 w-md-75 mb-5">

      <!-- Filter -->
      <div class="accordion  mx-auto w-md-75 row mt-5" id="filterAcc">
        <div class="col-md-12">
          <div class="accordion-item ">
            <h2 class="accordion-header" id="filter">    
              <button 
              class="accordion-button collapsed bg-light" 
              type="button" 
              data-bs-toggle="collapse"
              data-bs-target="#collapseFilter"
              style="font-weight: 600; font-size: 1.2rem;"
              ><i class="fa-solid fa-filter me-3"></i>Filters</button>
            </h2>
            <div class="accordion-collapse collapse" id="collapseFilter" data-bs-parent="filterAcc">
              <div class="accordion-body position-relative">
                <div class="row mx-auto mt-2">
                  <div class="col-12 mx-auto">
                    <div class="input-group">
                      <span class="input-group-text">
                        <i class="fa-solid fa-signature"></i>
                      </span>
                      
                      <input
                      type="text"
                      class="form-control"
                      id="customerNameFilter"
                      placeholder="Filter by Customer Name"
                      />
                                             
                    </div>      
                  </div>
                  
                </div>
                <div class="row mx-auto mt-3">
                  <div class="col-6">
                    <div class="form-floating">
                      <input
                        type="date"
                        class="form-control form-floating"
                        id="startDate"
                        placeholder="Filter by Date"
                      />
                      <label for="dateFilter">Start Date</label>
                    </div>
                    
                  </div>
                  <div class="col-6">
                    <div class="form-floating">
                      <input
                        type="date"
                        class="form-control form-floating"
                        id="endDate"
                        placeholder="Filter by Date"
                      />
                      <label for="dateFilter">End Date</label>
                    </div>
                    
                  </div>
                </div>

                <div class="row mx-auto mt-3">
                  <div class="col form-check form-switch ps-2">
                    <input class="form-check-input ms-1" type="checkbox" id="isArchived" name="isArchived" style="height: 75%; width: 40px">
                    <label class="form-check-label" for="isArchived" style="white-space: pre-wrap; font-size: 1rem;">  Include Archived Invoices?</label>
                  </div>
                </div>
                <br>

                <div class="container d-flex justify-content-end gap-2">
                  <button type="button" class="btn btn-primary btn-sm order-button" id="applyFilter" onclick="applyFilter()">Apply</button>
                  <button type="button" class="btn btn-danger btn-sm order-button" id="resetFilter" onclick="resetFilter()">Reset</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="accordion mx-auto w-md-75 row mt-5" id="accordionExample">
        <div class="col-md-12">
          <div class="accordion-item">
            <div 
              class="accordion-header bg-light text-center" 
              id="mainHeader"
              style="padding: var(--bs-accordion-btn-padding-y) var(--bs-accordion-btn-padding-x); font-weight: 500; font-size: 1.2rem;">
              List of Invoices
            </div>
          </div>
          <% slicedData.forEach(invoice => { %>
          <div class="accordion-item realContents">
            <h2 class="accordion-header" id="headingOne">
              <button
                class="accordion-button collapsed"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#collapse<%= invoice._id %>"
                aria-expanded="true"
                aria-controls="collapse<%= invoice._id %>"
              >
                <%= invoice.deliveryDate%> - <%= invoice.customerName %> (<%= invoice.productContent.length + invoice.hamperContent.length %> items)
              </button>
            </h2>
            <div
              id="collapse<%= invoice._id %>"
              class="accordion-collapse collapse realStuff"
              aria-labelledby="headingOne"
              data-bs-parent="#accordionExample"
            >
              <div class="accordion-body position-relative">
                <% if(!invoice.isArchived){ %>
                <div class="container button-container-1">
                  <button 
                    class="btn btn-primary order-button btn-sm position-sticky end-0" 
                    onclick="redirect('/invoiceDashboard/editInvoice/<%= invoice._id %>')"
                    >
                      <i class="fa-solid fa-pen-to-square"></i>
                  </button>
                  <button 
                    class="btn btn-success order-button btn-sm position-sticky end-0"  
                    onclick="redirect('/invoiceDashboard/printInvoice/<%= invoice._id %>')"
                    >
                    <i class="fa-solid fa-print"></i>
                  </button>
                  <button 
                    class="btn btn-secondary  order-button btn-sm position-sticky end-0"  
                    onclick="redirect('/invoiceDashboard/archiveInvoice/<%= invoice._id %>')"
                    >
                    <i class="fa-solid fa-archive"></i>
                  </button>
                  <button 
                    class="btn btn-danger order-button btn-sm position-sticky end-0"  
                    onclick="redirect('/invoiceDashboard/deleteInvoice/<%= invoice._id %>')"
                    >
                    <i class="fa-solid fa-trash"></i>
                  </button>
                </div>
                <% } %>
                
                <% if(invoice.oldProductId !== '' && invoice.oldProductId) {%>
                  Invoice Type: Taken from order sent on <%= invoice.updatedAt.split('T')[0] %><br>
                  <% if(invoice.modified) {%>
                    <strong>This invoice does NOT match the original order.</strong> <br>
                  <% } %>
                <% } else { %>
                  Invoice Type: Created from Scratch <br>
                <% } %>

                <% if(invoice.isArchived) {%>
                  <strong>This invoice has been archived, and thus cannot be modified. </strong> <br>
                <% } %>
                <br>

                Customer Name: <%= invoice.customerName %> <br>
                Customer Address: <%= invoice.customerAddress %> <br>
                Customer Note: <%= invoice.customerNote %> <br> <br>

                Delivery Date: <%= invoice.deliveryDate %> <br>
                Invoice Note: <%= invoice.details %> <br>

                <div hidden id="customerName"><%= invoice.customerName %></div>
                <div hidden id="deliveryDate"><%= invoice.deliveryDateOld.split('T')[0] %></div>
                <div hidden id="isArchived"><%= invoice.isArchived %></div>

                <div
                  class="table-responsive flipped-container"
                >
                  <table
                    class="table table-borderless align-middle text-star flipped"
                  >
                    <thead>
                      <tr>
                        <th class="col-4">Name</th>
                        <th class="col-4">Price</th>
                        <th class="col-2">Quantity</th>
                        <th class="col-2">Subtotal</th>
                      </tr>
                    </thead>
                    <tbody class="table-group-divider">
                      <% var total = 0; %>
                      <% invoice.productContent.forEach(product => { %>
                        <tr>
                          <td><%= product.name %></td>
                          <% if(product.discount === 0) { %>
                            <td><%= formatRupiah(product.priceValue) %> (<%= product.priceType %>)</td>
                            <% var subtotal = product.priceValue; %>
                          <% } else { %>
                            <% var discountValue = parseInt(product.priceValue * product.discount / 100); %>
                            <% var subtotal = product.priceValue - discountValue; %>
                            <td><%= formatRupiah(product.priceValue) %> (<%= product.priceType %>) <br> -  <%= formatRupiah(discountValue) %> (<%= product.discount %>%) <br> = <%= formatRupiah(subtotal) %></td>
                          <% } %>
                          <td>x  <%= product.quantity %></td>
                          <td><%= formatRupiah(subtotal * product.quantity) %></td>
                          <% total += subtotal * product.quantity; %>
                        </tr>
                      <% }) %>
                      <% invoice.hamperContent.forEach(hamper => { %>
                        <tr>
                          <td><%= hamper.name %></td>
                          <% if(hamper.discount === 0) { %>
                            <td><%= formatRupiah(hamper.priceValue) %> (<%= hamper.priceType %>)</td>
                            <% var subtotal = hamper.priceValue; %>
                          <% } else { %>
                            <% var discountValue = parseInt(hamper.priceValue * hamper.discount / 100); %>
                            <% var subtotal = hamper.priceValue - discountValue; %>
                            <td><%= formatRupiah(hamper.priceValue) %> (<%= hamper.priceType %>) <br> -  <%= formatRupiah(discountValue) %> (<%= hamper.discount %>%) <br> = <%= subtotal %></td>
                          <% } %>
                          <td>x  <%= hamper.quantity %></td>
                          <td><%= formatRupiah(subtotal * hamper.quantity) %></td>
                          <% total += subtotal * hamper.quantity; %>
                        </tr>
                      <% }) %>

                      
                      <tr>
                        <td colspan="3" style="text-align: right;"><strong>Total</strong></td>
                        <td><%= formatRupiah(total) %></td>
                      </tr>

                      <% if(invoice.invoiceDiscount !== 0) { %>
                        <tr>
                          <td colspan="3" style="text-align: right;"><strong>Discount (<%= invoice.invoiceDiscount %>%)</strong></td>
                          <td><%= formatRupiah(parseInt(invoice.invoiceDiscount * total / 100)) %></td>
                        </tr>
                        <tr>
                          <td colspan="3" style="text-align: right;"><strong>Final Total</strong></td>
                          <td><%= formatRupiah(total - parseInt(invoice.invoiceDiscount * total / 100)) %></td>
                        </tr>
                      <% } %>
                    </tbody>
                    <tfoot>
                      
                    </tfoot>
                  </table>
                </div>
                
                
              </div>
            </div>
          </div>
          <% }) %>
        </div>
        
      </div>
      
    </div>
  </body>
  <script
    src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
    crossorigin="anonymous"
  ></script>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  <script>
    function redirect(domain) {
      window.location.href = domain
    }

    function applyFilter() {
      let customerName = document.querySelector("#customerNameFilter").value.toLowerCase() || "";
      let startDate = new Date(document.querySelector("#startDate").value || "1970-01-01");
      let endDate = new Date(document.querySelector("#endDate").value || "2050-12-31");
      let isArchived = document.querySelector("#isArchived").checked
      console.log(customerName, startDate, endDate);
      const contents = document.querySelectorAll(".realContents");
      contents.forEach((content) => {
          const currentCustomerName = content
            .querySelector("#customerName")
            .textContent.toLowerCase();
          const currentDeliveryDate = new Date(content
            .querySelector("#deliveryDate").textContent);
          const currentIsArchived = content.querySelector("#isArchived").textContent;
          console.log(currentCustomerName, customerName);
          console.log(isArchived,currentIsArchived);
          if (currentCustomerName.includes(customerName) && (currentDeliveryDate >= startDate && currentDeliveryDate <= endDate && ((isArchived === false && currentIsArchived === 'false') || (isArchived == true))) ) {
            content.style.display = "";
          } else {
            content.style.display = "none";
          }
        });
    }

    function resetFilter() {
      document.querySelector("#customerNameFilter").value = "";
      document.querySelector("#startDate").value = "";
      document.querySelector("#endDate").value = "";
      document.querySelector("#isArchived").checked = false;
      applyFilter();
    }

    applyFilter();
  </script>
</html>
