<script>
import ZohoSearch from "@/components/ZohoSearch.vue";
import LoadingButton from "@/components/LoadingButton.vue";
// import { Printd } from "printd";
import { Howl, Howler } from "howler";
import { getUploadedImage } from "@/helpers/utils.js";
import { tableMixin } from "@/helpers/tables.mixin";

export const saleSubmittedSound = new Howl({
  src: ["/beep/beep.wav"],
});
export const cartItemAddedSound = new Howl({
  src: ["/beep/beep.mp3"],
});
Howler.volume(0.5);

export default {
  name: "Sale",
  components: {
    ZohoSearch,
    LoadingButton,
  },
  mixins: [tableMixin],
  data: () => ({
    items: [],
    itemsFilter: {
      group: "all",
      category: null,
    },
    newSale: {
      committed_date: new Date().toLocaleString("fr-CA").slice(0, 10),
      payment_method: null,
      payment_ref: null,
      total_amount: 0,
      discounted_total: 0,
      payment_date: new Date().toLocaleString("fr-CA").slice(0, 10),
      amount_paid: 0,
      discount_amount: 0,
      comment: "",
      amount_remain: 0,
      discount: 0,
    },
    paymentModes: [],
    searchKey: null,
    orderItems: [],
    record: null,
    showPayment: false,
    categories: [],
    savedOrder: {},
    activeList: true,
    activeGrid: false,
    task: "GETTING_SALING_PRODUCT",
    detailModal: null,
    selectedProduct: null,
  }),
  computed: {
    products() {
      let keyword = this.searchKey && this.searchKey.toLowerCase();
      let rows = this.items;
      if (keyword) {
        rows = rows.filter(
          (row) => String(row.name).toLowerCase().indexOf(keyword) > -1
        );
      }
      if (this.itemsFilter.category != null) {
        rows = rows.filter(
          (row) => row.category_id == this.itemsFilter.category
        );
      }
      return rows;
    },
    cartItems() {
      return this.orderItems.map((item) => item.id);
    },
    hasUnavailableBatch() {
      return this.orderItems.some((order) => !order.batch);
    },
    subTotal() {
      return this.orderItems.reduce((a, b) => a + b.quantity * b.price, 0);
    },
    isFetchingProducts() {
      return (
        this.$store.state.isLoading &&
        this.$store.state.loadingTask == this.task
      );
    },
  },
  beforeMount() {
    let reference = this.$route.params.reference;
    if (reference) {
      this.$http
        .get(`stock/pos/sales/details/${reference}`)
        .then((response) => {
          this.record = response.data.record;
          this.orderItems = [...response.data.items, ...this.orderItems];
          const sale = response.data.record;
          this.newSale.id = sale.id;
          this.newSale.client_id = sale.client_id;
          this.newSale.total_amount = sale.discounted_total;
          this.newSale.amount_paid = sale.amount_paid;
          this.newSale.amount_remain = sale.amount_remain;
          this.newSale.committed_date = new Date(sale.committed_date)
            .toLocaleString("fr-CA")
            .slice(0, 10);
          if (sale.payments && sale.payments.length) {
            this.newSale.payment_method = sale.payments[0].payment_type;
          }
        });
    }
  },
  mounted() {
    this.$store.commit("SET_AJAX_TASK", this.task);
    this.$http
      .all([
        this.$http.get("stock/categories"),
        this.$http.get("stock/pos/items"),
        this.$http.get("stock/pos/payments-modes"),
      ])
      .then(
        this.$http.spread((responseOne, responseTwo, responseThree) => {
          this.items = responseTwo.data.rows;
          this.categories = responseOne.data.rows;
          this.paymentModes = responseThree.data.rows;
        })
      );
    this.detailModal = new bootstrap.Modal(
      document.getElementById("detail-modal")
    );
  },
  methods: {
    getUploadedImage,
    addToCart(item, sign = "+") {
      if (this.cartItems.includes(item.id)) {
        let index = this.cartItems.indexOf(item.id);
        if (sign == "-") {
          this.orderItems[index].quantity -= 1;
          if (this.orderItems[index].quantity <= 0)
            this.orderItems.splice(index, 1);
        } else {
          if (this.orderItems[index].quantity < item.qty)
            this.orderItems[index].quantity += 1;
        }
      } else {
        if (item.qty > 0) this.orderItems.push({ ...item, ...{ quantity: 1 } });
      }
      cartItemAddedSound.play();
    },

    handleRemove(i) {
      this.orderItems.splice(i, 1);
    },

    goToPayment() {
      this.showPayment = true;
      this.calculateDiscountedAmount();
    },
    handleGoBack() {
      this.showPayment = false;
    },

    calculateDiscountedAmount() {
      this.newSale.total_amount = this.subTotal;
      let discountAmount =
        (Number(this.subTotal) * Number(this.newSale.discount)) / 100;
      this.newSale.discount_amount = discountAmount;
      this.newSale.discounted_total =
        Number(this.subTotal) - Number(discountAmount);
      this.newSale.amount_paid = Number(this.subTotal) - Number(discountAmount);
      this.newSale.amount_remain =
        Number(this.newSale.discounted_total) -
        Number(this.newSale.amount_paid);
    },
    calculateAmountRemain() {
      this.newSale.amount_remain =
        Number(this.newSale.discounted_total) -
        Number(this.newSale.amount_paid);

      if (this.newSale.amount_remain < 0) {
        this.newSale.amount_paid = this.subTotal;
        this.newSale.amount_remain = 0;
      }
    },
    handleLayout(type) {
      if (type === "list") {
        this.activeList = true;
        this.activeGrid = false;
      }

      if (type === "grid") {
        this.activeGrid = true;
        this.activeList = false;
      }
    },
    handleSubmit() {
      this.newSale.items = this.orderItems;
      this.$http
        .post(
          "stock/pos/sales/store",
          this.$helper.generateFormData(this.newSale)
        )
        .then((response) => {
          if (response.data.status) {
            this.$notify({
              type: "success",
              text: "Sale saved sucessfully",
            });
            Object.assign(this.newSale, {});
            this.newSale.items = [];
            this.orderItems = [];
            this.showPayment = false;
            this.savedOrder = response.data.order;
            saleSubmittedSound.play();

            setTimeout(() => {
              // const styles = [
              //   `${location.origin}/css/custom.css`,
              //   `${location.origin}/css/bootstrap.min.css`,
              //   `${location.origin}/css/thermal-print.css`,
              // ];
              // const d = new Printd();
              // const printEl = document.querySelector("#print-container");
              // d.print(printEl, styles);
              this.$router.push({
                name: "ReceiptViewLarge",
                params: {
                  reference: response.data.order.reference,
                  action: "view",
                },
                query: {
                  origin: "receiptview",
                },
              });
            }, 250);
          }
        });
    },
    productDetailModal(row) {
      this.selectedProduct = row;
      this.$store.commit("SET_AJAX_TASK", "SHOW-PRODUCT-DETAIL");
      setTimeout(this.detailModal.show(), 1);
    },
  },
};
</script>
<template>
  <div class="" style="min-height: 90vh">
    <div class="" style="max-height: 100% !important">
      <div class="row">
        <div class="col-12">
          <div
            class="page-title-box d-flex align-items-center justify-content-between"
          >
            <h3 class="mb-0">{{ $trans("Selling Panel") }}</h3>
            <div class="font-size-10">
              <span
                title="Out of stock"
                class="badge rounded-circle header-profile-user badge-soft-danger"
                data-key="t-hot"
                ><i
                  class="uil uil-ban fs-4"
                  style="position: relative; top: 3px"
                ></i
              ></span>
              Out of Stock
            </div>
            <div class="font-size-10">
              <span
                title="In Stock"
                class="badge rounded-circle header-profile-user badge-soft-success"
                data-key="t-hot"
                ><i
                  class="uil uil-arrow-up-right fs-4"
                  style="position: relative; top: 3px"
                ></i
              ></span>
              In Stock
            </div>
            <div class="font-size-10">
              <span
                title="Under 5Qty Please Refill"
                class="badge rounded-circle header-profile-user badge-soft-warning"
                data-key="t-hot"
                ><i
                  class="uil uil-process fs-4"
                  style="position: relative; top: 3px"
                ></i
              ></span>
              Under Five Qty
            </div>
            <div class="page-title-right">
              <div
                class="d-flex flex-wrap align-items-start justify-content-md-end mt-2 mt-md-0 gap-2"
              >
                <div>
                  <ul class="nav nav-pills">
                    <li class="nav-item">
                      <a
                        class="nav-link"
                        :class="{ active: activeList }"
                        href="javascript:void(0)"
                        title="List"
                        alt="List"
                        @click="handleLayout('list')"
                      >
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          width="20"
                          height="20"
                          fill="currentColor"
                          class="bi bi-list-ul"
                          viewBox="0 0 16 16"
                        >
                          <path
                            fill-rule="evenodd"
                            d="M5 11.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm-3 1a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm0 4a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm0 4a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"
                          />
                        </svg>
                      </a>
                    </li>
                    <li class="nav-item">
                      <a
                        class="nav-link"
                        :class="{ active: activeGrid }"
                        href="javascript:void(0)"
                        title="Grid"
                        alt="Grid"
                        @click="handleLayout('grid')"
                      >
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          width="20"
                          height="20"
                          fill="currentColor"
                          class="bi bi-grid"
                          viewBox="0 0 16 16"
                        >
                          <path
                            d="M1 2.5A1.5 1.5 0 0 1 2.5 1h3A1.5 1.5 0 0 1 7 2.5v3A1.5 1.5 0 0 1 5.5 7h-3A1.5 1.5 0 0 1 1 5.5v-3zM2.5 2a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-.5-.5h-3zm6.5.5A1.5 1.5 0 0 1 10.5 1h3A1.5 1.5 0 0 1 15 2.5v3A1.5 1.5 0 0 1 13.5 7h-3A1.5 1.5 0 0 1 9 5.5v-3zm1.5-.5a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-.5-.5h-3zM1 10.5A1.5 1.5 0 0 1 2.5 9h3A1.5 1.5 0 0 1 7 10.5v3A1.5 1.5 0 0 1 5.5 15h-3A1.5 1.5 0 0 1 1 13.5v-3zm1.5-.5a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-.5-.5h-3zm6.5.5A1.5 1.5 0 0 1 10.5 9h3a1.5 1.5 0 0 1 1.5 1.5v3a1.5 1.5 0 0 1-1.5 1.5h-3A1.5 1.5 0 0 1 9 13.5v-3zm1.5-.5a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-.5-.5h-3z"
                          />
                        </svg>
                      </a>
                    </li>
                  </ul>
                </div>
                <div>
                  <a
                    href="/leads/clients"
                    class="btn btn-primary"
                    style="color: white"
                    ><i class="uil uil-plus me-1"></i>
                    {{ $trans("Add New Client") }}</a
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-xl-5 col-lg-7 col-md-7 pe-1">
          <div class="card">
            <div class="card-body p-3">
              <div class="d-flex w-100 pb-3 border-bottom flex-nowrap">
                <div
                  class="input-group search-area right d-lg-inline-flex d-none"
                >
                  <input
                    type="text"
                    class="form-control"
                    placeholder="Search here..."
                    v-model="searchKey"
                  />
                  <span class="input-group-text"
                    ><a href="javascript:void(0)"
                      ><i class="uil uil-search"></i></a
                  ></span>
                </div>
                <div class="ms-2" v-if="categories.length">
                  <ZohoSearch
                    label="name"
                    placeholder="Category"
                    v-model="itemsFilter.category"
                    :records="categories"
                    fetch-flag="SEARCH_FOR_CATEGORIES"
                  ></ZohoSearch>
                </div>
                <div class="ms-2">
                  <button
                    class="btn btn-primary btn-sm d-flex align-items-center"
                    type="button"
                    @click="
                      () => {
                        searchKey = null;
                        itemsFilter.category = null;
                      }
                    "
                  >
                    <i class="uil uil-refresh fs-4"></i
                    ><span class="ms-1">{{ $trans("Clear") }}</span>
                  </button>
                </div>
              </div>
              <div
                class="d-flex justify-content-center loader-container"
                v-if="isFetchingProducts && !products.length"
              >
                <div class="lds-ellipsis">
                  <div></div>
                  <div></div>
                  <div></div>
                  <div></div>
                </div>
              </div>
              <div class="items-list scrollable-content w-ful" v-else>
                <div v-if="products.length">
                  <div class="table-responsive" v-if="activeList == true">
                    <table class="table table-light table-hover mb-0">
                      <thead>
                        <tr>
                          <th>#</th>
                          <th class="text-center">Name</th>
                          <th>Qty</th>
                          <th>Price</th>
                          <th>status</th>
                        </tr>
                      </thead>

                      <tbody>
                        <tr
                          v-for="(item, i) in products"
                          :key="item.id"
                          @click.prevent="addToCart(item)"
                          :class="{
                            'added-item': cartItems.includes(item.id),
                          }"
                          class="font-size-11"
                        >
                          <td class="fw-medium">{{ i + 1 }}</td>
                          <td class="fw-bold font-size-11">
                            {{ item.name.toUpperCase() }}
                            <label v-if="item.packaging" class="font-size-10"
                              >[{{ item.packaging }}]</label
                            >
                          </td>

                          <td>
                            <span
                              class="btn font-size-11 btn-outline-purple btn-rounded fw-bold"
                              >{{ item.qty }}</span
                            >
                          </td>
                          <td class="fw-bold">
                            {{ $helper.formatNumber(item?.price) }}
                          </td>
                          <td>
                            <span
                              title="Out of stock"
                              class="spinner-grow text-danger btn btn-outline-danger badge rounded-circle header-profile-user badge-soft-danger"
                              v-if="item.qty <= 0"
                              data-key="t-hot"
                              ><i
                                class="uil uil-ban fs-4"
                                style="position: relative; top: 3px"
                              ></i
                            ></span>
                            <span
                              title="In Stock"
                              class="badge rounded-circle header-profile-user badge-soft-success"
                              v-if="item.qty > 5"
                              data-key="t-hot"
                              ><i
                                class="uil uil-arrow-up-right fs-4"
                                style="position: relative; top: 3px"
                              ></i
                            ></span>
                            <span
                              title="Under 5Qty Please Refill"
                              class="badge rounded-circle header-profile-user badge-soft-warning"
                              v-if="item.qty <= 5 && item.qty > 0"
                              data-key="t-hot"
                              ><i
                                class="uil uil-process fs-4"
                                style="position: relative; top: 3px"
                              ></i
                            ></span>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                  <div
                    class="row row-cols-3 row-cols-lg-4 d-flex py-2 px-3"
                    v-if="activeGrid == true"
                  >
                    <a
                      href="javascript:void(0)"
                      class="col tags border product-sales"
                      :class="{ 'added-item': cartItems.includes(item.id) }"
                      v-for="item in products"
                      :key="item.id"
                      @click.prevent="addToCart(item)"
                      :product-content="item.name"
                    >
                      <div class="pt-2 position-relative">
                        <span
                          title="Out of stock"
                          class="badge rounded-circle header-profile-user badge-soft-danger"
                          v-if="item.qty <= 0"
                          data-key="t-hot"
                          ><i
                            class="uil uil-ban fs-4"
                            style="position: relative; top: 3px"
                          ></i
                        ></span>
                        <span
                          title="In Stock"
                          class="badge rounded-circle header-profile-user badge-soft-success"
                          v-if="item.qty > 5"
                          data-key="t-hot"
                          ><i
                            class="uil uil-arrow-up-right fs-4"
                            style="position: relative; top: 3px"
                          ></i
                        ></span>
                        <span
                          title="Under 5Qty Please Refill"
                          class="badge rounded-circle header-profile-user badge-soft-warning"
                          v-if="item.qty <= 5 && item.qty > 0"
                          data-key="t-hot"
                          ><i
                            class="uil uil-process fs-4"
                            style="position: relative; top: 3px"
                          ></i
                        ></span>
                        <span
                          title="In Stock"
                          data-key="t-hot"
                          style="position: relative; left: 75%; bottom: 33px"
                          ><h6 style="font-weight: bold; font-family: nunito">
                            {{ item.qty }}
                          </h6>
                        </span>
                        <div class="text-center w-100">
                          <img
                            :src="
                              item.image
                                ? getUploadedImage(item.image)
                                : '/img/default.jpg'
                            "
                            style="
                              width: 60px;
                              height: 60px;
                              border: 3px solid #d4d8d891;
                            "
                            class="rounded-circle"
                          />
                          <div class="product-desc my-2">
                            <h6
                              class="mb-1 fw-normal text-truncate font-size-11"
                            >
                              {{ item.name }}
                            </h6>
                            <p
                              class="mb-0 fs-6 fw-bold text-dark badge badge-success"
                            >
                              FB {{ $helper.formatNumber(item?.price) }}
                            </p>
                          </div>
                        </div>
                      </div>
                    </a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-xl-7 col-lg-5 col-md-5 ps-1">
          <div class="card">
            <div class="card-body p-3">
              <div
                class="position-absolute top-0 bottom-0 start-0 end-0 bg-white w-100 px-4 py-3 over-content"
                style="z-index: 999"
                v-show="showPayment"
              >
                <div class="d-flex w-100">
                  <a
                    href="javascript:void(0)"
                    class="btn btn-primary rounded-circle btn-icon btn-xs"
                    style="padding: 0.208rem 0.238rem"
                    @click.prevent="handleGoBack"
                  >
                    <svg
                      width="20"
                      height="20"
                      viewBox="0 0 24 24"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        d="M21.0001 9.99999H7.82806L11.4141 6.41399C11.7784 6.03679 11.98 5.53158 11.9754 5.00719C11.9709 4.48279 11.7605 3.98117 11.3897 3.61035C11.0189 3.23954 10.5173 3.0292 9.99286 3.02464C9.46847 3.02009 8.96327 3.22167 8.58606 3.58599L1.58606 10.586C1.21112 10.961 1.00049 11.4697 1.00049 12C1.00049 12.5303 1.21112 13.0389 1.58606 13.414L8.58606 20.414C8.77056 20.605 8.99124 20.7574 9.23525 20.8622C9.47926 20.967 9.7417 21.0222 10.0073 21.0245C10.2728 21.0268 10.5362 20.9762 10.782 20.8756C11.0278 20.7751 11.2511 20.6266 11.4389 20.4388C11.6266 20.251 11.7751 20.0277 11.8757 19.7819C11.9763 19.5361 12.0269 19.2727 12.0246 19.0072C12.0223 18.7416 11.9671 18.4792 11.8623 18.2352C11.7574 17.9912 11.6051 17.7705 11.4141 17.586L7.82806 14H21.0001C21.5305 14 22.0392 13.7893 22.4143 13.4142C22.7893 13.0391 23.0001 12.5304 23.0001 12C23.0001 11.4696 22.7893 10.9609 22.4143 10.5858C22.0392 10.2107 21.5305 9.99999 21.0001 9.99999Z"
                        fill="#fff"
                      ></path>
                    </svg>
                  </a>
                  <h6 class="mb-0 text-nowrap ms-auto fw-bold">
                    {{ $trans("Complete Payment") }}
                  </h6>
                </div>
                <div class="total-section invoice-discount" id="total-section">
                  <div class="ember-view">
                    <div class="ember-view">
                      <div class="ember-view collapse show" style="">
                        <div class="total-row gross-total mt-0">
                          <div class="total-label">{{ $trans("Total") }}</div>
                          <div class="total-amount">
                            FB {{ $helper.formatNumber(subTotal) }}
                          </div>
                        </div>

                        <div class="total-row sub-total mt-0">
                          <div class="total-label">
                            {{ $trans("Paid Amount") }} <br />
                          </div>
                          <div class="total-amount">
                            <div class="input-group">
                              <span class="input-group-text">FB</span>
                              <input
                                type="number"
                                @keyup="calculateAmountRemain"
                                v-model="newSale.amount_paid"
                                class="form-control"
                                placeholder="Directly paid"
                              />
                            </div>
                          </div>
                        </div>

                        <div class="total-row sub-total mt-0">
                          <div class="total-label">
                            {{ $trans("Amount Due") }}<br />
                          </div>
                          <div class="total-amount">
                            FB
                            {{ $helper.formatNumber(newSale.amount_remain) }}
                          </div>
                        </div>
                        <template
                          v-if="newSale.amount_paid && newSale.amount_paid > 0"
                        >
                          <div class="total-row sub-total mt-0">
                            <div class="total-label">
                              <span class="required">{{
                                $trans("Payment Mode")
                              }}</span>
                              <br />
                            </div>
                            <div class="total-amount">
                              <select
                                class="form-select"
                                v-model="newSale.payment_method"
                              >
                                <option value="null" hidden selected>
                                  {{ $trans("Select Option") }}
                                </option>
                                <option
                                  :value="row.id"
                                  v-for="row in paymentModes"
                                  :key="row.id"
                                >
                                  {{ row.name }}
                                </option>
                              </select>
                            </div>
                          </div>

                          <div class="total-row sub-total mt-0">
                            <div class="total-label">
                              {{ $trans("Payment Ref") }} <br />
                            </div>
                            <div class="total-amount">
                              <input
                                type="text"
                                class="form-control"
                                v-model="newSale.payment_ref"
                                placeholder="Payment REF"
                              />
                            </div>
                          </div>
                        </template>
                        <div
                          class="total-row sub-total mt-0"
                          v-if="
                            newSale.amount_remain && newSale.amount_remain != 0
                          "
                        >
                          <div class="total-label">
                            {{ $trans("Due Date") }} <br />
                          </div>
                          <div class="total-amount">
                            <input
                              type="date"
                              class="form-control"
                              v-model="newSale.payment_date"
                              placeholder="Due Date"
                            />
                          </div>
                        </div>
                        <div class="total-row sub-total mt-0 mb-3">
                          <textarea
                            v-model="newSale.comment"
                            rows="3"
                            class="form-control"
                            style="height: auto !important"
                            placeholder="Write some comment"
                          ></textarea>
                        </div>
                        <div class="text-center">
                          <LoadingButton
                            task="PLACING_ORDER"
                            class="btn btn-primary btn-block w-100"
                            type="button"
                            @clicked="handleSubmit"
                            :disabled="
                              newSale.amount_paid &&
                              newSale.amount_paid > 0 &&
                              !newSale.payment_method
                            "
                          >
                            <template #caption>
                              <svg
                                xmlns="http://www.w3.org/2000/svg"
                                width="20"
                                height="20"
                                fill="currentColor"
                                class="bi bi-patch-check-fill"
                                viewBox="0 0 16 16"
                              >
                                <path
                                  d="M10.067.87a2.89 2.89 0 0 0-4.134 0l-.622.638-.89-.011a2.89 2.89 0 0 0-2.924 2.924l.01.89-.636.622a2.89 2.89 0 0 0 0 4.134l.637.622-.011.89a2.89 2.89 0 0 0 2.924 2.924l.89-.01.622.636a2.89 2.89 0 0 0 4.134 0l.622-.637.89.011a2.89 2.89 0 0 0 2.924-2.924l-.01-.89.636-.622a2.89 2.89 0 0 0 0-4.134l-.637-.622.011-.89a2.89 2.89 0 0 0-2.924-2.924l-.89.01-.622-.636zm.287 5.984-3 3a.5.5 0 0 1-.708 0l-1.5-1.5a.5.5 0 1 1 .708-.708L7 8.793l2.646-2.647a.5.5 0 0 1 .708.708z"
                                />
                              </svg>
                              {{ $trans("Confirm and Save") }}</template
                            >
                          </LoadingButton>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="d-flex align-items-center w-100">
                <div class="me-2 w-50">
                  <ZohoSearch
                    url="stock/clients/search"
                    label="name"
                    placeholder="Customer"
                    v-model="newSale.client_id"
                    :load-defaults="true"
                    :records="[
                      {
                        id: $trans('Walk-in'),
                        name: $trans('Walk-in Customer'),
                      },
                    ]"
                    fetch-flag="SEARCHING_FOR_CLIENTS"
                    ref="CustomersSelector"
                  ></ZohoSearch>
                </div>
                <div class="w-50">
                  <input
                    type="date"
                    class="form-control"
                    placeholder="Date"
                    v-model="newSale.committed_date"
                  />
                </div>
              </div>
              <template v-if="orderItems.length">
                <div class="pb-5 pt-1 cart-container scrollable-content">
                  <div
                    class="table-responsive"
                    style="max-height: calc(100vh - 15rem)"
                  >
                    <table
                      class="table table-hover table-wrap mb-0 align-middle table-check"
                    >
                      <thead class="table-light">
                        <tr>
                          <th></th>
                          <th>Batch</th>
                          <th>Name</th>
                          <th class="text-center">Qty</th>
                          <th class="text-center">Price</th>
                          <th>Total</th>
                          <th></th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr
                          class="border-bottom"
                          v-for="(item, i) in orderItems"
                          :key="i"
                          style="font-family: nunito !important"
                        >
                          <td>
                            <span
                              title="Under 5Qty Please Refill"
                              class="badge rounded-circle header-profile-user badge-soft-primary"
                              v-if="item.product_changes.length > 0"
                              data-key="t-hot"
                              @click="productDetailModal(item)"
                              ><i
                                class="uil uil-process fs-4"
                                style="position: relative; top: 3px"
                              ></i
                            ></span>
                          </td>
                          <td>
                            <select
                              class="form-control"
                              style="width: 100px"
                              v-model="orderItems[i].batch"
                            >
                              <option :value="undefined" hidden disabled>
                                Batch
                              </option>
                              <option v-for="batch in item.product_changes">
                                {{ batch.batch_nber }}
                              </option>
                            </select>
                          </td>
                          <td class="fw-medium font-size-12">
                            {{ item.name }}
                          </td>
                          <td>
                            <div class="dz-stepper small-stepper border-2">
                              <div
                                class="input-group bootstrap-touchspin bootstrap-touchspin-injected"
                              >
                                <span
                                  class="input-group-btn input-group-prepend"
                                  ><button
                                    class="btn btn-primary bootstrap-touchspin-down"
                                    type="button"
                                    @click="addToCart(item, '-')"
                                  >
                                    -
                                  </button></span
                                ><input
                                  class="stepper form-control"
                                  type="text"
                                  v-model="item.quantity"
                                /><span
                                  class="input-group-btn input-group-append"
                                  ><button
                                    class="btn btn-primary bootstrap-touchspin-up"
                                    type="button"
                                    @click="addToCart(item, '+')"
                                  >
                                    +
                                  </button></span
                                >
                              </div>
                            </div>
                          </td>
                          <td>
                            <input
                              type="text"
                              style="width: 120px"
                              class="form-control text-center"
                              v-model="orderItems[i].price"
                            />
                          </td>
                          <td>
                            <h6
                              class="mb-0 fw-bold"
                              style="font-family: nunito !important"
                            >
                              {{
                                $helper.formatNumber(item.price * item.quantity)
                              }}
                            </h6>
                          </td>
                          <td>
                            <a
                              class="text-danger"
                              href="javascript:void(0)"
                              @click.prevent="handleRemove(i)"
                            >
                              <svg
                                xmlns="http://www.w3.org/2000/svg"
                                width="25"
                                height="25"
                                fill="currentColor"
                                class="bi bi-trash"
                                viewBox="0 0 16 16"
                              >
                                <path
                                  d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5Zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5Zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6Z"
                                />
                                <path
                                  d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1ZM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118ZM2.5 3h11V2h-11v1Z"
                                />
                              </svg>
                            </a>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
                <div
                  class="position-sticky w-100 bottom-0 py-3"
                  style="z-index: 998"
                >
                  <h6 class="d-flex align-items-center w-100">
                    <span class="fw-border"
                      >{{ $trans("Payable Amount") }}:</span
                    >
                    <span class="text-primary ms-auto">
                      FB {{ $helper.formatNumber(subTotal) }}
                    </span>
                  </h6>
                  <button
                    class="w-100 btn btn-primary"
                    type="button"
                    @click="goToPayment"
                    :disabled="!newSale.client_id || hasUnavailableBatch"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="20"
                      height="20"
                      fill="currentColor"
                      class="bi bi-arrow-right-circle-fill"
                      viewBox="0 0 16 16"
                    >
                      <path
                        d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0zM4.5 7.5a.5.5 0 0 0 0 1h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 1 0-.708.708L10.293 7.5H4.5z"
                      />
                    </svg>
                    {{ $trans("Continue To Payment") }}
                  </button>
                </div>
              </template>
              <template v-else>
                <div class="cart-container justify-content-center">
                  <div
                    class="d-flex align-items-center justify-content-between"
                  >
                    <div class="p-2 w-100">
                      <div class="ant-empty">
                        <div class="ant-empty-description">
                          <img src="/img/not found.svg" width="300" />
                        </div>
                        <br />
                        <p class="alert alert-warning">
                          {{ $trans("No Product Found in Cart") }}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div
    id="print-container"
    class="d-none"
    v-if="savedOrder && Object.keys(savedOrder).length > 0"
  >
    <div class="py-1 border-bottom border-dashed">
      <div class="invoice-title">
        <h4 class="float-end font-size-15">
          Invoice #{{ $helper.padNumber(savedOrder.id) }}
          <span
            class="badge bg-success font-size-12 ms-2"
            v-if="savedOrder.paid"
            >Paid</span
          >
          <span class="badge bg-danger font-size-12 ms-2" v-else>Loan</span>
        </h4>
        <div class="mb-4">
          <img src="/img/company.png" alt="logo" height="50" />
        </div>
      </div>
      <hr />
      <div
        class="row"
        style="
          border: 2px solid #ddd;
          padding: 10px 10px;
          width: 100%;
          margin-left: 1px;
        "
      >
        <div class="col-6">
          <div>
            <h5 class="font-size-15 mb-1">
              <span class=""
                >{{ $trans("RECEIPT NO") }}:
                <b>#{{ $helper.padNumber(savedOrder.id) }}</b></span
              >
            </h5>
          </div>
          <div>
            <h5 class="font-size-15 mb-1">
              <span class=""
                >{{ $trans("Served By") }}:
                <b>{{
                  savedOrder.creator ? savedOrder.creator.name : "Administrator"
                }}</b></span
              >
            </h5>
          </div>
          <div>
            <h5 class="font-size-15 mb-1">
              <span
                >{{ $trans("Date") }}:
                <b>{{ $helper.formatDate(savedOrder.committed_date) }}</b></span
              >
            </h5>
          </div>
          <div v-if="savedOrder.paid == 0">
            <h5 class="font-size-15 mb-1">
              <span
                >Due Date:
                <b>{{ $helper.formatDate(savedOrder.payment_date) }}</b></span
              >
            </h5>
          </div>
        </div>
        <div class="col-6">
          <div class="text-muted text-sm-end">
            <div>
              <h5 class="font-size-15 mb-1">
                <span class=""
                  >{{ $trans("Client") }}:
                  <b>{{
                    savedOrder.client
                      ? savedOrder.client.name
                      : $trans("Walk-in Customer")
                  }}</b></span
                >
              </h5>
            </div>
          </div>
          <div class="text-muted text-sm-end">
            <div>
              <h5 class="font-size-15 mb-1">
                <span class=""
                  >{{ $trans("Tin number") }}:
                  <b>{{
                    savedOrder.client ? savedOrder.client.tinnumber : "---"
                  }}</b></span
                >
              </h5>
            </div>
          </div>
          <div class="text-muted text-sm-end">
            <div>
              <h5 class="font-size-15 mb-1">
                <span class=""
                  >{{ $trans("Phone") }}:
                  <b>{{
                    savedOrder.client ? savedOrder.client.phone : "---"
                  }}</b></span
                >
              </h5>
            </div>
          </div>
        </div>
      </div>
    </div>
    <h5 class="font-size-15">Items Description</h5>
    <div class="py-1 border-bottom border-dashed">
      <table class="table table-sm table-borderless mb-1">
        <thead>
          <tr>
            <th style="width: 70px">No.</th>
            <th>Ref Code</th>
            <th class="text-center">Item</th>
            <th>LOT Exp</th>
            <th>P/U</th>
            <th>Qty</th>
            <th class="text-center">Total</th>
          </tr>
        </thead>
        <tr v-for="(item, i) in savedOrder.items" :key="'order_items' + i">
          <td>
            <span>{{ i + 1 }}</span>
          </td>
          <td>{{ item.code }}</td>
          <td>
            <span class="font-size-12 fw-bold">{{
              item.name.toUpperCase()
            }}</span>
          </td>
          <td>{{ item.expiration_date || "---" }}</td>
          <td>
            <span>{{ $helper.formatNumber(item.price) }}</span>
          </td>
          <td>
            <span>{{ item.quantity }} {{ item.unit }}</span>
          </td>
          <td class="fw-bold">
            <span>FB {{ $helper.formatNumber(item.amount) }}</span>
          </td>
        </tr>
      </table>
    </div>
    <div class="py-1 border-bottom border-dashed">
      <table class="table table-sm table-borderless mb-2">
        <tr>
          <td>
            <span class="fw-bolder">{{ $trans("Grand Total") }}</span>
          </td>
          <td class="text-end text-nowrap">
            <span class="h5 mb-0 fw-bold"
              >FBU {{ $helper.formatNumber(savedOrder.discounted_total) }}</span
            >
          </td>
        </tr>
      </table>

      <table
        class="table table-sm table-borderless mb-2"
        v-if="savedOrder.paid == 0"
      >
        <tr>
          <td>
            <span class="fw-bolder text-success">{{
              $trans("Paid Total Amount")
            }}</span>
          </td>
          <td class="text-end text-nowrap">
            <span class="h5 mb-0 text-success"
              >FBU {{ $helper.formatNumber(savedOrder.amount_paid) }}</span
            >
          </td>
        </tr>

        <tr>
          <td>
            <span class="fw-bolder text-danger">{{
              $trans("Remain Total Amount")
            }}</span>
          </td>
          <td class="text-end text-nowrap">
            <span class="h5 mb-0 text-danger"
              >FBU {{ $helper.formatNumber(savedOrder.amount_remain) }}</span
            >
          </td>
        </tr>
      </table>
      <span style="font-family: nunito"
        >Total In Words:
        <span class="text-primary font-size-11 fw-bold">{{
          NumInWords(savedOrder.discounted_total).toUpperCase()
        }}</span></span
      >
      <div class="font-size-12 d-flex justify-content-between">
        <div>
          <hr />
          <h5>Terms and Conditions</h5>
          <span>
            <b>Payment Terms: 100%</b> Payment in advance/on delivery<br />
            <b>Warranty:</b> N/A<br />
            <b>Delivery time:</b> 5 working days from the date of payment and
            purchase order<br />
            <b>Offer validity:</b> 7 days<br />
          </span>
          <hr />
          <h5>Account Information</h5>
          <span>
            Beneficiary Bank: <b>BANK OF KIGALI PLC</b> <br />
            ACCOUNT NAME: <b>KING'S MEDICAL LTD</b><br />
            ACCOUNT NUMBER: <b>100082610628</b> FBU<br />
            MTN MOMO PAY CODE: <b>852230</b></span
          >
        </div>
        <div class="font-size-12" style="font-family: nunito">
          <span>Name: <b>NIYIBIZI FABRICE</b></span
          ><br />
          <span><img src="/img/signature.png" /></span><br />
          <span class="font-size-16">King's Medical Ltd</span>
        </div>
      </div>
    </div>
  </div>

  <div
    class="modal fade bs-example-modal-lg"
    id="detail-modal"
    tabindex="-1"
    aria-labelledby="detail-modalLabel"
    aria-hidden="true"
  >
    <div class="modal-dialog modal-lg modal-dialog-centered">
      <div class="modal-content" v-if="selectedProduct != null">
        <div class="modal-header bg-primary">
          <h5 class="modal-title text-white" id="detail-modalLabel">
            Product Details #<span class="fw-bold text-white"
              >{{ selectedProduct.name }}
              <i class="font-size-13">{{ selectedProduct.packaging }}</i></span
            >
          </h5>
        </div>
        <div class="modal-body p-2">
          <div class="row g-gs align-items-center">
            <div class="col-12">
              <div class="table-responsive">
                <table
                  class="table font-size-13 table-light table-hover table-striped align-middle table-nowrap table-check"
                  id="pagination-table"
                >
                  <tbody>
                    <tr>
                      <td class="fw-bold">Current Quantity:</td>
                      <td class="fw-bold text-purple">
                        {{ selectedProduct.qty || "N/A" }}
                        {{
                          selectedProduct.unit ? selectedProduct.unit.name : ""
                        }}
                      </td>
                    </tr>
                    <tr>
                      <td class="fw-bold">Category:</td>
                      <td class="fw-bold text-purple">
                        {{
                          selectedProduct.category
                            ? selectedProduct.category.name
                            : "N/A"
                        }}
                      </td>
                    </tr>
                  </tbody>
                </table>
                <table
                  class="table font-size-13 table-light table-hover table-striped align-middle table-nowrap table-check"
                  id="pagination-table"
                >
                  <thead>
                    <tr>
                      <th>#</th>
                      <th>Batch number</th>
                      <th>Quantity</th>
                      <th>Price</th>
                      <th>Expiration date</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr
                      v-for="(
                        productChange, i
                      ) in selectedProduct.product_changes"
                      :key="i"
                    >
                      <td>{{ i + 1 }}</td>
                      <td>{{ productChange.batch_nber }}</td>
                      <td class="fw-bold">{{ productChange.quantity }}</td>
                      <td>{{ productChange.price }}</td>
                      <td>{{ productChange.expiration_date }}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style>
.tags {
  display: inline;
  position: relative;
}

.tags:hover:after {
  background: #333;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 5px;
  bottom: -34px;
  color: #fff;
  content: attr(data-gloss);
  left: 50%;
  transform: translateX(-50%);
  padding: 5px 15px;
  position: absolute;
  z-index: 98;
  max-width: 200px; /* Set the maximum width for the tooltip */
  white-space: normal; /* Allow the text to wrap */
  word-wrap: break-word; /* Break words if they exceed the max width */
}

.tags:hover:before {
  border: solid;
  border-color: #333 transparent;
  border-width: 0 6px 6px 6px;
  bottom: -4px;
  content: "";
  left: 50%;
  position: absolute;
  z-index: 99;
}
table {
  border: 1px solid #ddd;
}
@media (max-width: 600px) {
  .tags:hover:after {
    width: auto; /* Allow the tooltip to adjust its width based on content */
    max-width: 80%; /* Limit the maximum width */
    white-space: break-spaces; /* Allow text to break into multiple lines if needed */
    word-break: break-word; /* Break words to prevent overflow */
    bottom: -50px; /* Adjust tooltip position for mobile */
  }
}
</style>
