<!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="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css"
    />
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.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/main.css" /> -->
    <link rel="stylesheet" href="../../styles/orderDashboard.css" />
    <link rel="shortcut icon" href="../icon.png" type="image/x-icon" />
    <title>Edit Order</title>
  </head>

  <body>
    <!-- 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">
            <a href="/orderDashboard" class="nav-link">Orders</a>
          </li>
          <li class="nav-item">
            <a href="/orderDashboard/products" class="nav-link">Products</a>
          </li>
          <li class="nav-item">
            <a href="/orderDashboard/hampers" class="nav-link">Hampers</a>
          </li>
          <li class="nav-item">
            <a href="/orderDashboard/customers" class="nav-link">Customers</a>
          </li>
          <li class="nav-item">
            <a href="/orderDashboard/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">Order Account </p>
        <button class="btn btn-light me-3" onclick="redirect('/logout')">Logout</button>
      </div>
    </nav>

    <!-- Wrapper -->
    <form
      class="container mx-auto mt-5 row mb-lg-0 px-0"
      id="myForm"
      action="/orderDashboard/editOrder/<%= orderData._id %>"
      method="post"
    >
      <!-- Left Side -->
      <div class="col-lg addOrderLeft mb-5">
        <h1>‚úçÔ∏èEdit Orderüßæ</h1>
        <br />

        <div class="sizeWarning">This sub-domain is not intended to be viewed in a small resolution. Please rotate your device to proceed.</div>


        <!-- Select Option for Customer -->
        <div
          class="btn-group d-flex justify-content-center"
          role="group"
          aria-label="Basic radio toggle button group"
          onchange="changeCustomerType()"
        >
          <input
            type="radio"
            class="btn-check"
            name="customerType"
            value="existing"
            id="btnradio1"
            autocomplete="off"
            checked
          />
          <label class="btn btn-outline-primary order-button" for="btnradio1"
            >Existing Customer</label
          >

          <input
            type="radio"
            class="btn-check"
            name="customerType"
            value="new"
            id="btnradio2"
            autocomplete="off"
          />
          <label class="btn btn-outline-primary order-button" for="btnradio2"
            >New Customer</label
          >
        </div>
        <br />

        <!-- Product Contents -->
        <div class="form-group">
          <label for="contents">Product Contents</label>

          <!-- Selector -->
          <div class="row m-0">
            <div class="col mx-0 px-0 pe-2">
              <select
                name="productContentInput"
                id="productContentInput"
                class="form-select"
                data-placeholder="Choose a product"
                onchange="addProductToOrder()"
              >
                <option disabled selected value="null">Select a product</option>
                <% products.forEach(product => { %>
                <option value="<%= product._id %>"><%= product.name %></option>
                <% }) %>
              </select>
            </div>
            <!-- <div class="col-2 col-xxl-1 mx-0 px-0">
              <button
                class="btn btn-primary btn-sm form-control specialFocus"
                type="button"
                onclick="addProductToOrder()"
              >
                <i class="fa-solid fa-plus"></i>
              </button>
            </div> -->
          </div>

          <br />
        </div>

        <!-- Hamper Contents -->
        <div class="form-group">
          <label for="contents">Hamper Contents</label>

          <!-- Selector -->
          <div class="row m-0">
            <div class="col mx-0 px-0 pe-2">
              <select
                name="hamperContentInput"
                id="hamperContentInput"
                class="form-select"
                data-placeholder="Choose a hamper"
                onchange="addHamperToOrder()"
              >
                <option disabled selected value="null">Select a hamper</option>
                <% hampers.forEach(hamper => { %>
                <option value="<%= hamper._id %>"><%= hamper.name %></option>
                <% }) %>
              </select>
            </div>
            <!-- <div class="col-2 col-xxl-1 mx-0 px-0">
              <button
                class="btn btn-primary btn-sm form-control specialFocus"
                type="button"
                onclick="addHamperToOrder()"
              >
                <i class="fa-solid fa-plus"></i>
              </button>
            </div> -->
          </div>

          <br />
        </div>

        <!-- Existing Customer Selector -->
        <div class="form-group existingCustomerContainer">
          <label for="existingCustomer" class="form-label"
            >Existing Customer</label
          >
          <select
            class="form-select"
            name="existingCustomer"
            id="existingCustomer"
            required
          >
            <option disabled value="">Select existing customer</option>
            <!-- prettier-ignore -->
            <% customers.forEach(customer => { %>
            <!-- prettier-ignore -->
            <% if(customer._id === orderData.customerId) { %>
            <option value="<%= customer._id %>" selected>
              <%= customer.name %>
            </option>
            <% } else { %>
            <option value="<%= customer._id %>"><%= customer.name %></option>
            <% } %> <% }); %>
          </select>
          <br />
        </div>

        <!-- New Customer Container -->
        <div class="newCustomerContainer" hidden>
          <!-- <hr class="mt-2" /> -->
          <div class="form-group">
            <label for="customerName" class="form-label">Customer Name</label>
            <input
              type="text"
              class="form-control"
              name="customerName"
              id="customerName"
              placeholder="Enter Customer Name"
            />
          </div>
          <br />
          <div class="form-group">
            <label for="customerAddress" class="form-label"
              >Customer Address</label
            >
            <input
              type="text"
              class="form-control"
              name="customerAddress"
              id="customerAddress"
              placeholder="Enter Customer Address"
            />
          </div>
          <br />
          <div class="form-group">
            <label for="customerNote" class="form-label">Customer Note</label>
            <input
              type="text"
              class="form-control"
              name="customerNote"
              id="customerNote"
              placeholder="Enter Customer Note"
            />
          </div>
          <br />
          <!-- <hr class="mt-2" /> -->
        </div>

        <!-- Delivery Date -->
        <div class="form-group">
          <label for="deliveryDate" class="form-label">Delivery Date</label>
          <input
            type="date"
            class="form-control"
            name="deliveryDate"
            id="deliveryDate"
            placeholder="Enter Delivery Date"
            value="<%= orderData.deliveryDateOld.split('T')[0] %>"
          />
        </div>
        <br />

        <!-- Order Discount -->
        <div class="form-group">
          <label for="orderDiscount" class="form-label">Order Discount</label>
          <div class="input-group">
            <input
              type="number"
              class="form-control"
              name="orderDiscount"
              id="orderDiscount"
              placeholder="Enter Order Discount"
              step="0.01"
              min="0"
              max="100"
              value="<%= orderData.orderDiscount %>"
            />
            <div class="input-group-text">%</div>
          </div>
        </div>
        <br />

        <!-- Order Note -->
        <div class="form-group">
          <label for="orderNote" class="form-label">Order Note</label>
          <input
            type="text"
            class="form-control"
            name="orderNote"
            id="orderNote"
            placeholder="Enter Order Note"
            value="<%= orderData.details %>"
          />
        </div>

        <br />

        <!-- Submit Buttons -->
        <div class="container w-100 d-flex justify-content-end p-0">
          <button
            type="button"
            class="btn btn-primary form-btn"
            onclick="validateContents()"
          >
            Submit
          </button>
          <button
            type="button"
            class="btn btn-primary form-btn ms-2"
            onclick="redirect('/orderDashboard')"
          >
            Cancel
          </button>
        </div>
      </div>

      <!-- Order Display -->
      <div class="container col-lg border-lg-start ms-lg-5 ps-md-5">
        <h3 class="text-center">Order Contents‚úçÔ∏è</h3>
        <div class="container table-responsive mt-4 px-0">
          <table
            class="table realContents w-100 mx-auto text-center align-middle"
          >
            <thead>
              <tr>
                <th>Item Name</th>
                <th>Price Type</th>
                <th>Quantity</th>
                <th>Discount</th>
                <th>Options</th>
              </tr>
            </thead>
            <tbody
              class="realContentsBody align-content-center border-top"
            ></tbody>
          </table>
        </div>
      </div>
    </form>
  </body>

  <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.0/dist/jquery.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.full.min.js"></script>
  <script>
    function redirect(domain) {
      window.location.href = domain;
    }

    function changeCustomerType() {
      let customerType = document.querySelector(
        "input[name='customerType']:checked"
      ).value;
      if (customerType === "new") {
        document
          .querySelector(".newCustomerContainer")
          .removeAttribute("hidden");
        document
          .querySelector(".existingCustomerContainer")
          .setAttribute("hidden", true);
        document.querySelector("#customerName").setAttribute("required",true);
        document.querySelector('#existingCustomer').removeAttribute("required");
      } else {
        document
          .querySelector(".newCustomerContainer")
          .setAttribute("hidden", true);
        document
          .querySelector(".existingCustomerContainer")
          .removeAttribute("hidden");
        document.querySelector("#existingCustomer").setAttribute("required",true);
        document.querySelector('#customerName').removeAttribute("required");
      }
    }

    $(document).ready(function() {
        $("#existingCustomer").select2({
            theme: "bootstrap-5",
            width: $(this).data("width")
                ? $(this).data("width")
                : $(this).hasClass("w-100")
                ? "100%"
                : "style",
            placeholder: $(this).data("placeholder"),
        });
        $("#productContentInput").select2({
          theme: "bootstrap-5",
          width: $(this).data("width")
            ? $(this).data("width")
            : $(this).hasClass("w-100")
            ? "100%"
            : "style",
          placeholder: $(this).data("placeholder"),
        });

        $("#hamperContentInput").select2({
          theme: "bootstrap-5",
          width: $(this).data("width")
            ? $(this).data("width")
            : $(this).hasClass("w-100")
            ? "100%"
            : "style",
          placeholder: $(this).data("placeholder"),
        });
    });


    function advanceTab(el) {
      let nextBtn = el.parentElement.parentElement.querySelector(".btn");
      console.log(nextBtn);
      nextBtn.setAttribute("tabIndex", "0");
      setTimeout(function () {
        nextBtn.focus();
      }, 20);
    }

    function addProductToOrder() {
      var selectedProductId = document.getElementById(
        "productContentInput"
      ).value;
      var selectedProductName = document.getElementById("productContentInput")
        .options[document.getElementById("productContentInput").selectedIndex]
        .text;

      if (!selectedProductId || selectedProductId === "null") {
        alert("Please select a product.");
        return;
      }

      var realContents = document.querySelector(".realContentsBody");
      var newProductEntry = document.createElement("tr");

      var columns = [
        { content: selectedProductName, classNames: ["col-3","name"] },
        {
          content: getProductPriceInput(selectedProductId),
          classNames: ["col","priceInput"],
        },
        {
          content:
            '<input type="number" class="form-control text-center w-75 mx-auto" name="quantities[]" value="1" step="0.01" min="0.01">',
          classNames: ["col-2", "text-center", "px-4","quantity"],
        },
        {
          content: '<input type="number" class="form-control text-center w-75 mx-auto" name="discounts[]" value="0" step="0.01" min="0" max="100">',
          classNames: ["col-2","text-center","px-4","discount"],
        },
        {
          content:
            `<button class="btn btn-danger btn-sm" type="button" onclick="removeThisProduct(this)">
              <i class="fa-solid fa-trash"></i>
              </button>
              <input type="hidden" name="contents[]" value="${selectedProductId}">
              <input type="hidden" name="${selectedProductId}_contentType" value="product">`,
          classNames: ["col-1", "text-center","trash"],
        },
      ];

      columns.forEach((column) => {
        var td = document.createElement("td");
        td.innerHTML = column.content;
        column.classNames.forEach((className) => td.classList.add(className));
        newProductEntry.appendChild(td);
      });

      realContents.appendChild(newProductEntry);
      document.querySelector(`option[value="${selectedProductId}"]`).remove();
      document.getElementById("productContentInput").value = "null";
    }

    function addHamperToOrder() {
      var selectedHamperId = document.getElementById(
        "hamperContentInput"
      ).value;
      var selectedHamperName = document.getElementById("hamperContentInput")
        .options[document.getElementById("hamperContentInput").selectedIndex]
        .text;

      if (!selectedHamperId || selectedHamperId === "null") {
        alert("Please select a hamper.");
        return;
      }

      var realContents = document.querySelector(".realContentsBody");
      var newProductEntry = document.createElement("tr");

      var columns = [
        { content: selectedHamperName, classNames: ["col-3","name"] },
        {
          content: getHamperPriceInput(selectedHamperId),
          classNames: ["col","priceInput"],
        },
        {
          content:
            '<input type="number" class="form-control text-center w-75 mx-auto" name="quantities[]" value="1" step="0.01" min="0.01">',
          classNames: ["col-2", "text-center", "px-4","quantity"],
        },
        {
          content: '<input type="number" class="form-control text-center w-75 mx-auto" name="discounts[]" value="0" step="0.01" min="0" max="100">',
          classNames: ["col-2","text-center","px-4","discount"],
        },
        {
          content:
            `<button class="btn btn-danger btn-sm" type="button" onclick="removeThisHamper(this)">
              <i class="fa-solid fa-trash"></i>
              </button>
              <input type="hidden" name="contents[]" value="${selectedHamperId}">
              <input type="hidden" name="${selectedHamperId}" value="hamper">`,
          classNames: ["col-1", "text-center","trash"],
        },
      ];

      columns.forEach((column) => {
        var td = document.createElement("td");
        td.innerHTML = column.content;
        column.classNames.forEach((className) => td.classList.add(className));
        newProductEntry.appendChild(td);
      });

      realContents.appendChild(newProductEntry);
      document.querySelector(`option[value="${selectedHamperId}"]`).remove();
      document.getElementById("hamperContentInput").value = "null";
    }


    function getProductPriceInput(productId, priceType = false, priceValue = "") {
      let products = <%- JSON.stringify(products) %> ;
      let selectedProduct = products.find(product => product._id === productId);
      let inputHTML = `
      <select
        name="${productId}_priceType"
        id="${productId}_priceType"
        class="form-select"
        data-placeholder="Choose a price type"
        onchange="updatePriceType(this)"
      >
      `;
      console.log(selectedProduct.prices);
      Object.entries(selectedProduct.prices).forEach(([key,value]) => {
        if(priceType === key){
            inputHTML += `<option value="${key}" price-value="${value}" selected>${key}: ${value}</option>`
        }
        else{
            inputHTML += `<option value="${key}" price-value="${value}">${key}: ${value}</option>`
        }
      })
      if(priceType === 'custom'){
        inputHTML += `<option value="custom" selected>Custom</option><input type="number" name="${productId}_customPrice" class="form-control" placeholder="Insert a custom price" value="${priceValue}"></select>`
      }
      else {
        inputHTML += `<option value="custom">Custom</option><input type="number" name="${productId}_customPrice" class="form-control" placeholder="Insert a custom price" hidden></select>`
      }
      return inputHTML;
    }

    function getHamperPriceInput(hamperId, priceType = false, priceValue = "") {
      let hampers = <%- JSON.stringify(hampers) %> ;
      let selectedHamper = hampers.find(hamper => hamper._id === hamperId);
      let inputHTML = `
      <select
        name="${hamperId}_priceType"
        id="${hamperId}_priceType"
        class="form-select"
        data-placeholder="Choose a price type"
        onchange="updatePriceType(this)"
      >
      `;
      console.log(selectedHamper.prices);
      Object.entries(selectedHamper.prices).forEach(([key,value]) => {
        if(priceType === key){
            inputHTML += `<option value="${key}" price-value="${value}" selected>${key}: ${value}</option>`
        }
        else{
            inputHTML += `<option value="${key}" price-value="${value}">${key}: ${value}</option>`
        }
      })
      if(priceType === 'custom'){
        inputHTML += `<option value="custom" selected>Custom</option><input type="number" name="${hamperId}_customPrice" class="form-control" placeholder="Insert a custom price" value="${priceValue}"></select>`
      }
      else {
        inputHTML += `<option value="custom">Custom</option><input type="number" name="${hamperId}_customPrice" class="form-control" placeholder="Insert a custom price" hidden></select>`
      }
      return inputHTML;
    }


    function updatePriceType(el) {
      if(el.value === 'custom'){
        el.nextElementSibling.removeAttribute("hidden");
      }
      else{
        el.nextElementSibling.setAttribute("hidden",true);
      }
    }

    function removeThisProduct(el) {
      trElement = el.parentElement.parentElement;
      productId = el.nextElementSibling.value;
      console.log(el.nextElementSibling.value);
      productName = trElement.querySelector(".name").innerHTML;

      newOption = document.createElement("option");
      newOption.value = productId;
      newOption.text = productName;

      selectElement = document.getElementById("productContentInput");
      selectElement.add(newOption);

      var options = Array.from(selectElement.options);
      options.sort(function (a, b) {
        return a.text.localeCompare(b.text);
      });

      selectElement.innerHTML = "";
      options.forEach(function (option) {
        selectElement.add(option);
      });
      productId = trElement.remove();
    }

    function removeThisHamper(el) {
      let trElement = el.parentElement.parentElement;
      let hamperId = el.nextElementSibling.value;
      console.log(el.nextElementSibling.value);
      let hamperName = trElement.querySelector(".name").innerHTML;

      newOption = document.createElement("option");
      newOption.value = hamperId;
      newOption.text = hamperName;

      selectElement = document.getElementById("hamperContentInput");
      selectElement.add(newOption);

      var options = Array.from(selectElement.options);
      options.sort(function (a, b) {
        return a.text.localeCompare(b.text);
      });

      selectElement.innerHTML = "";
      options.forEach(function (option) {
        selectElement.add(option);
      });
      hamperId = trElement.remove();
    }


    function formatRupiah(number) { return number.toLocaleString('id-ID', {
    style: 'currency', currency: 'IDR' }); }
    function validateContents() {
      let contents = document.querySelector(".realContentsBody");
      if (!document.querySelector("#myForm").reportValidity()) {
        return;
      }
      if (contents.children.length) {
        document.querySelector("form").submit();
      } else {
        alert("Contents must have at least one product!");
      }
    }

    // Populating data
    document.addEventListener('DOMContentLoaded',() => {
        // prettier-ignore
        let products = <%- JSON.stringify(orderData.productContent) %>;
        let hampers = <%- JSON.stringify(orderData.hamperContent) %>;
        let realContents = document.querySelector('.realContentsBody');
        products.forEach(product => {
            var newProductEntry = document.createElement("tr");
            var selectedProductId = product.productId;
            var selectedProductName = product.name;
            var columns = [
                { content: selectedProductName, classNames: ["col-3","name"] },
                {
                content: getProductPriceInput(selectedProductId, product.priceType, product.priceValue),
                classNames: ["col","priceInput"],
                },
                {
                content:
                    `<input type="number" class="form-control text-center w-75 mx-auto" name="quantities[]" value="${product.quantity}" step="0.01" min="0.01">`,
                classNames: ["col-2", "text-center", "px-4","quantity"],
                },
                {
                content: `<input type="number" class="form-control text-center w-75 mx-auto" name="discounts[]" value="${product.discount}" step="0.01" min="0">`,
                classNames: ["col-2","text-center","px-4","discount"],
                },
                {
                content:
                    `<button class="btn btn-danger btn-sm" type="button" onclick="removeThisProduct(this)">
                    <i class="fa-solid fa-trash"></i>
                    </button>
                    <input type="hidden" name="contents[]" value="${selectedProductId}">
                    <input type="hidden" name="${selectedProductId}_contentType" value="product">`,
                classNames: ["col-1", "text-center","trash"],
                },
            ];

            columns.forEach((column) => {
                var td = document.createElement("td");
                td.innerHTML = column.content;
                column.classNames.forEach((className) => td.classList.add(className));
                newProductEntry.appendChild(td);
            });

            realContents.appendChild(newProductEntry);
            document.querySelector(`option[value="${selectedProductId}"]`).remove();
        })
        hampers.forEach(hamper => {
            var newHamperEntry = document.createElement("tr");
            var selectedHamperId = hamper.hamperId;
            var selectedHamperName = hamper.name;
            var columns = [
                { content: selectedHamperName, classNames: ["col-3","name"] },
                {
                content: getHamperPriceInput(selectedHamperId, hamper.priceType, hamper.priceValue),
                classNames: ["col","priceInput"],
                },
                {
                content:
                    `<input type="number" class="form-control text-center w-75 mx-auto" name="quantities[]" value="${hamper.quantity}" step="0.01" min="0.01">`,
                classNames: ["col-2", "text-center", "px-4","quantity"],
                },
                {
                content: `<input type="number" class="form-control text-center w-75 mx-auto" name="discounts[]" value="${hamper.discount}" step="0.01" min="0">`,
                classNames: ["col-2","text-center","px-4","discount"],
                },
                {
                content:
                    `<button class="btn btn-danger btn-sm" type="button" onclick="removeThisProduct(this)">
                    <i class="fa-solid fa-trash"></i>
                    </button>
                    <input type="hidden" name="contents[]" value="${selectedHamperId}">
                    <input type="hidden" name="${selectedHamperId}_contentType" value="hamper">`,
                classNames: ["col-1", "text-center","trash"],
                },
            ];

            columns.forEach((column) => {
                var td = document.createElement("td");
                td.innerHTML = column.content;
                column.classNames.forEach((className) => td.classList.add(className));
                newHamperEntry.appendChild(td);
            });

            realContents.appendChild(newHamperEntry);
            document.querySelector(`option[value="${selectedHamperId}"]`).remove();
        })
    })
  </script>
</html>
