import dayjs from "dayjs";
import { ref, onMounted } from "vue";
import { usePage } from "@inertiajs/vue3";
import { w as calculate_item, z as check_promotions, A as _sfc_main } from "./http-CDixhmav.js";
import { T } from "../ssr.js";
import "./LoadingButton-DREeyNQW.js";
const FormHelper = (form) => {
  const page = usePage();
  const selectedItem = ref(null);
  const openItemModal = ref(false);
  const formName = ref(T().current() + ".form");
  onMounted(async () => {
    if (formName.value.includes(".create") || formName.value.includes("pos")) {
      let saved_form = localStorage.getItem(formName.value);
      if (saved_form && dayjs().isSame(dayjs(saved_form._last_saved), "day")) {
        saved_form = JSON.parse(saved_form);
        Object.keys(saved_form).map((k) => {
          form[k] = saved_form[k];
        });
      }
    }
  });
  function resetForm() {
    localStorage.removeItem(formName.value);
    form.reset();
  }
  function saveForm(date) {
    if (formName.value.includes(".create") || formName.value.includes("pos")) {
      form.date_changed = date ? true : false;
      form._last_saved = dayjs().format("YYYY-MM-DD HH:mm:ss");
      localStorage.setItem(formName.value, JSON.stringify({ ...form, errors: {} }));
    }
  }
  function removeItem(item) {
    selectedItem.value = item.product_id;
    if (page.props.settings.pin_code && !page.props.auth.user.roles.find((r) => r.name == "Super Admin")) {
      page.props.ask_pin_code = true;
      return false;
    }
    deleteSelectedItem();
  }
  function deleteSelectedItem() {
    form.items = form.items.filter((i) => i.product_id != selectedItem.value);
    form.items = form.items.filter((i) => i.promo_product_id != selectedItem.value);
    selectedItem.value = null;
    openItemModal.value = false;
    saveForm();
  }
  function selectItem(item) {
    selectedItem.value = { ...item };
    openItemModal.value = true;
  }
  async function updateItem() {
    const index = form.items.findIndex((i) => i.product_id == selectedItem.value.product_id);
    form.items[index] = calculate_item({ ...selectedItem.value }, form.calculate_on);
    form.items = await check_promotions(form);
    selectedItem.value = null;
    openItemModal.value = false;
    saveForm();
  }
  return { openItemModal, selectItem, selectedItem, saveForm, resetForm, removeItem, updateItem };
};
const VariationSelection = () => {
  const currentItem = ref(null);
  const variantModal = ref(false);
  function deleteVariation(variation, item) {
    item.variations = item.variations.filter((v) => v.id != variation.id);
    item = item.variations && item.variations.length ? item : null;
    return item;
  }
  function emptyVariation(product) {
    return { id: null, meta: {}, code: null, quantity: 1, price: 0, product_id: product.id, unit_id: product.unit_id };
  }
  return { currentItem, deleteVariation, emptyVariation, variantModal, SelectVariant: _sfc_main };
};
export {
  FormHelper as F,
  VariationSelection as V
};
