<template>
    <LoadingComponent :props="loading" />

    <div class="md:w-[calc(100%-340px)] lg:w-[calc(100%-320px)] xl:w-[calc(100%-377px)]">
        <div class="grid grid-cols-7 gap-x-6 grid-flow-row">

            <div class="col-span-7 lg:col-span-5 order-2 lg:order-1">
                <div class="swiper pos-menu-swiper mb-6" v-if="categories.length > 1">
                    <Swiper dir="ltr" :speed="500" slidesPerView="auto" :spaceBetween="16" class="menu-slides">
                        <SwiperSlide class="!w-fit" v-for="(category, index) in categories" :key="category"
                            :class="category.id === props.search.item_category_id || (category.id === 0 && props.search.item_category_id === '') ? 'pos-group' : ''">
                            <router-link to="#" @click.prevent="setCategory(category.id)"
                                class="w-auto flex items-center text-center gap-3 p-2.5 rounded-lg border-b-2 border-transparent transition hover:bg-[#FFEDF4] hover:border-primary bg-white">
                                <img class="h-8 lg:h-9 drop-shadow-category" :src="category.thumb" alt="category">
                                <h3 class="text-xs leading-[16px] font-medium font-rubik">{{ category.name }}</h3>
                            </router-link>
                        </SwiperSlide>

                    </Swiper>
                </div>
            </div>
            <form @submit.prevent="search"
                class="flex items-center h-12 lg:h-[56px] leading-12 lg:leading-[56px] mb-4 rounded-lg bg-white col-span-7 lg:col-span-2 order-1 lg:order-2">
                <input type="text" v-model="props.search.name" :placeholder="$t('label.search_by_menu_item')"
                    class="w-full h-full px-5 rounded-tl-lg rounded-bl-lg border placeholder:text-xs placeholder:font-rubik placeholder:text-[#A0A3BD] border-[#EFF0F6]">
                <button type="submit"
                    class="flex-shrink-0 w-[38px] h-full text-center ltr:rounded-tr-lg ltr:rounded-br-lg rtl:rounded-tl-lg rtl:rounded-bl-lg bg-primary">
                    <i class="lab lab-search-normal text-white"></i>
                </button>
            </form>
        </div>
        <ItemComponent :items="items" v-if="items.length > 0" />

        <div class="mt-12" v-else>
            <div class="max-w-[250px] mx-auto">
                <img class="w-full mb-8" :src="setting.item_not_found" alt="image_order_not_found">
            </div>
            <p class="w-full text-sm mb-4 text-center text-black mx-auto">{{ $t('message.no_items_found') }}</p>
        </div>
    </div>


    <div id="pos-cart"
        class="db-pos-cartDiv fixed top-0 ltr:right-0 rtl:left-0 w-full h-dvh rounded-none z-50 md:z-10 md:top-[85px] ltr:md:right-5 rtl:md:left-5 md:w-[322px] lg:w-[305px] xl:w-[360px] md:h-[calc(100vh-85px)] md:rounded-lg overflow-y-auto thin-scrolling bg-white">
        <div class="p-4">
            <div class="md:hidden text-right mb-3">
                <button class="db-pos-cartCls" @click="closeCanvas('pos-cart')">
                    <i class="lab-close-circle-line font-fill-danger lab-font-size-24"></i>
                </button>
            </div>
            <div class="flex items-center w-full gap-4 mb-3">
                <div class="db-field flex-grow">
                    <vue-select
                        class="db-field-control text-sm rounded-lg appearance-none text-heading border-[#D9DBE9]"
                        id="customer" v-model="checkoutProps.form.customer_id" :options="customers" label-by="name"
                        value-by="id" :closeOnSelect="true" :searchable="true" :clearOnClose="true"
                        :placeholder="$t('label.select_customer')" :search-placeholder="$t('label.search_customer')" />
                </div>
                <div data-modal="#addCustomer" @click.prevent="addCustomers"
                    class="w-10 h-10 bg-primary rounded-lg flex items-center justify-center cursor-pointer">
                    <i class="fa-solid fa-circle-plus text-white"></i>
                </div>
            </div>

            <div class="p-3 pt-2 rounded-lg border border-[#D9DBE9] relative" v-if="checkoutProps.form.customer_id">
                <h4 class="text-sm font-medium mb-3">{{ $t('label.delivery_address') }}</h4>
                <button v-if="!customerAddress.id" @click="openAddressModal" data-modal="#addaddress" type="button"
                    class="absolute top-2 right-2 group text-xs capitalize font-medium flex items-center rounded-3xl py-1.5 px-3 gap-1 text-primary bg-[#FFEDF4] transition hover:text-white hover:bg-primary">
                    <i class="fa-solid fa-circle-plus"></i>
                    <span>{{ $t('button.add') }}</span>
                </button>
                <button v-else @click="editAddressModal(customerAddress)" data-modal="#addaddress" type="button"
                    class="absolute top-2 right-2 group text-xs capitalize font-medium flex items-center rounded-3xl py-1.5 px-3 gap-1 text-[#00749B] bg-[#D6F5FF] transition hover:text-white hover:bg-[#00749B]">
                    <svg class="fill-[#00749B] transition group-hover:fill-white" width="10" height="10"
                        viewBox="0 0 10 10" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path fill-rule="evenodd" clip-rule="evenodd"
                            d="M3.6882 9.01395L8.08139 3.33272C8.32015 3.02635 8.40504 2.67215 8.32546 2.31149C8.25648 1.98363 8.05486 1.67189 7.75243 1.43539L7.01493 0.849532C6.37293 0.33892 5.57706 0.392668 5.12076 0.978529L4.62732 1.61867C4.56365 1.69876 4.57957 1.81701 4.65916 1.88151C4.65916 1.88151 5.90602 2.88123 5.93255 2.90273C6.01744 2.98335 6.08111 3.09085 6.09703 3.21985C6.12356 3.47247 5.94846 3.70896 5.68848 3.74121C5.56645 3.75733 5.44972 3.71971 5.36483 3.64984L4.0543 2.60711C3.99063 2.55928 3.89512 2.56949 3.84207 2.63399L0.727569 6.66514C0.525949 6.91775 0.456974 7.24562 0.525949 7.56274L0.923883 9.28807C0.945106 9.37944 1.02469 9.44394 1.1202 9.44394L2.87111 9.42244C3.18945 9.41707 3.48658 9.27194 3.6882 9.01395ZM6.13984 8.47663H8.99489C9.27344 8.47663 9.5 8.70613 9.5 8.98831C9.5 9.27103 9.27344 9.5 8.99489 9.5H6.13984C5.86129 9.5 5.63473 9.27103 5.63473 8.98831C5.63473 8.70613 5.86129 8.47663 6.13984 8.47663Z" />
                    </svg>
                    <span>{{ $t('button.edit') }}</span>
                </button>
                <div id="orderdelivery" class="h-auto transition">
                    <div v-if="customerAddress.id" class="p-3 rounded-lg w-full border border-[#D9DBE9]">
                        <div class="flex gap-2 text-xs font-normal items-center">
                            <i class="lab-location mt-0.5 text-paragraph"></i>
                            <span class="text-sm leading-6 text-heading">{{ customerAddress?.address }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="p-3 pt-2 mt-3 rounded-lg border border-[#D9DBE9]">
                <h4 class="text-sm font-medium mb-3">{{ $t('label.select_days') }}</h4>
                <div class="pos-dayslider">
                    <Swiper dir="ltr" v-if="deliveryDays.length > 0" :speed="1000" slidesPerView="auto"
                        :spaceBetween="16" class="">
                        <SwiperSlide v-for="deliveryDay in deliveryDays" :key="deliveryDay"
                            class="!w-fit !h-10 cursor-pointer py-2 px-3 rounded-lg !flex items-center border transition border-[#F7F7FC] bg-[#F7F7FC] daytabs"
                            @click.prevent="updateDeliveryDays($event, deliveryDay.number_of_days)"
                            :class="cartDeliveryDays === deliveryDay.number_of_days ? 'active' : ''">
                            <label class="flex items-center gap-3 ">
                                <div class="custom-radio sm">
                                    <input type="radio" id="1day" name="days" class="custom-radio-field"
                                        :checked="cartDeliveryDays === deliveryDay.number_of_days">
                                    <span class="custom-radio-span"></span>
                                </div>
                                <h3 class="block capitalize text-xs text-nowrap">{{
                                    deliveryDay.number_of_days }} {{
                                        deliveryDay.number_of_days > 1 ? $t('label.days') :
                                            $t('label.day') }}</h3>
                            </label>
                        </SwiperSlide>
                    </Swiper>
                </div>
            </div>
            <div class="p-3 pt-2 mt-3 rounded-lg border border-[#D9DBE9] flex flex-col" v-if="cartDeliveryDays">
                <div class="flex justify-between items-center">
                    <h4 class="text-sm font-medium">{{ $t('label.select_dates') }}</h4>
                    <i class="lab lab-calendar lab-font-size-24 lab-color-pink cursor-pointer"
                        @click="openDatesModal"></i>
                </div>
                <div class="mb-2" v-for="(dates, monthYear) in groupedDates" :key="monthYear">
                    <p class="text-black/60 mb-1 leading-6">{{ monthYear }}</p>
                    <div class="flex flex-wrap items-center justify-start gap-2">
                        <span v-for="date in dates" :key="date" class="date">{{ new Date(date).getDate()
                        }}</span>
                    </div>
                </div>
            </div>


        </div>
        <table class="w-full">
            <thead class="bg-[#FFEDF4]">
                <tr class="h-9">
                    <th class="capitalize text-xs font-normal font-rubik text-left pl-3 text-heading"></th>
                    <th class="capitalize text-xs font-normal font-rubik text-left px-3 text-heading">
                        {{ $t('label.item') }}
                    </th>
                    <th class="capitalize text-xs font-normal font-rubik text-left px-3 text-heading">
                        {{ $t('label.qty') }}
                    </th>
                    <th class="capitalize text-xs font-normal font-rubik text-left px-3 text-heading">
                        {{ $t('label.price') }}
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(cart, index) in carts">
                    <td class="pl-3 py-3 last:pr-3 align-top border-b border-[#EFF0F6]">
                        <button @click.prevent="deleteCartItem(index)">
                            <i class="lab lab-trash-line-2 font-fill-danger"></i>
                        </button>
                    </td>
                    <td class="pl-3 py-3 last:pr-3 align-top border-b border-[#EFF0F6]">
                        <h3 class="capitalize text-xs font-rubik text-[#2E2F38]">{{ textShortener(cart.name, 25) }}</h3>
                        <p v-if="Object.keys(cart.item_variations.variations).length !== 0">
                            <span v-for="(variation, variationName, index) in cart.item_variations.names">
                                <span class="capitalize text-[10px] leading-4 font-rubik text-heading">{{
                                    variationName
                                }}: {{ variation }}
                                    <span v-if="index + 1 < Object.keys(cart.item_variations.names).length">,
                                        &nbsp;</span>
                                </span>
                            </span>
                        </p>
                        <ul v-if="cart.instruction !== ''">
                            <li v-if="cart.instruction !== ''" class="leading-4">
                                <span class="capitalize text-[10px] leading-4 font-rubik text-heading">
                                    {{ $t('label.instruction') }}:
                                </span>
                                <span class="capitalize text-[10px] leading-4 font-rubik">
                                    {{ textShortener(cart.instruction, 120) }}
                                </span>
                            </li>
                        </ul>
                    </td>
                    <td class="pl-3 py-3 last:pr-3 align-top border-b border-[#EFF0F6]">
                        <div class="flex items-center indec-group">
                            <button @click.prevent="cartQuantityDecrement(index)"
                                :class="cart.quantity === 1 ? 'fa-trash-can' : 'fa-minus'"
                                class="fa-solid text-[10px] w-[18px] h-[18px] leading-4 text-center rounded-full border transition text-primary border-primary hover:bg-primary hover:text-white indec-minus"></button>
                            <input v-on:keypress="onlyNumber($event)" v-on:keyup="cartQuantityUp(index, $event)"
                                type="number" :value="cart.quantity"
                                class="text-center w-7 text-xs font-semibold text-heading indec-value">
                            <button @click.prevent="cartQuantityIncrement(index)"
                                class="fa-solid fa-plus text-[10px] w-[18px] h-[18px] leading4 text-center rounded-full border transition text-primary border-primary hover:bg-primary hover:text-white indec-plus"></button>
                        </div>
                    </td>
                    <td class="pl-3 py-3 last:pr-3 align-top border-b border-[#EFF0F6] text-xs font-rubik text-heading">
                        {{
                            currencyFormat(cart.total, setting.site_digit_after_decimal_point,
                                setting.site_default_currency_symbol, setting.site_currency_position)
                        }}
                    </td>
                </tr>
            </tbody>
        </table>
        <div class="p-4">

            <ul class="flex flex-col gap-1.5 mb-4 mt-4 border-b border-dashed border-[#EFF0F6]">
                <li class="flex items-center justify-between">
                    <span class="text-sm font-rubik capitalize leading-6 text-[#2E2F38]">
                        {{ $t('label.cart_total') }}
                    </span>
                    <span class="text-sm font-rubik capitalize leading-6 text-[#2E2F38]">
                        {{
                            currencyFormat(subtotal, setting.site_digit_after_decimal_point,
                                setting.site_default_currency_symbol, setting.site_currency_position)
                        }}
                    </span>
                </li>
                <li class="flex items-center justify-between pb-2">
                    <span class="text-sm font-rubik capitalize leading-6 text-[#2E2F38]">
                        {{ $t('label.no_of_days') }}
                    </span>
                    <span class="text-sm font-rubik capitalize leading-6 text-[#2E2F38]">
                        {{ cartDeliveryDays }}
                    </span>
                </li>
            </ul>
            <ul class="flex flex-col gap-1.5 mb-4 mt-4 border-b border-dashed border-[#EFF0F6]">
                <li class="flex items-center justify-between">
                    <span class="text-sm font-rubik capitalize leading-6 text-[#2E2F38]">
                        {{ $t("label.subtotal") }}
                    </span>
                    <span class="text-sm font-rubik capitalize leading-6 text-[#2E2F38]">
                        {{
                            currencyFormat(subtotal * cartDeliveryDays,
                                setting.site_digit_after_decimal_point,
                                setting.site_default_currency_symbol, setting.site_currency_position)
                        }}
                    </span>
                </li>
                <li class="flex items-center justify-between">
                    <span class="text-sm font-rubik capitalize leading-6 text-[#2E2F38]">
                        {{ $t("label.tax") }}
                    </span>
                    <span class="text-sm font-rubik capitalize leading-6 text-[#2E2F38]">
                        {{
                            currencyFormat(totalTax * cartDeliveryDays,
                                setting.site_digit_after_decimal_point,
                                setting.site_default_currency_symbol, setting.site_currency_position)
                        }}
                    </span>
                </li>
                <li class="flex items-center justify-between pb-2">
                    <span class="text-sm font-rubik capitalize leading-6">{{ $t("label.delivery_charge") }}</span>
                    <span class="text-sm font-rubik capitalize leading-6 font-medium text-[#1AB759]">{{
                        currencyFormat(delivery_charge, setting.site_digit_after_decimal_point,
                            setting.site_default_currency_symbol, setting.site_currency_position)
                    }}</span>
                </li>
            </ul>
            <ul class="flex flex-col gap-1.5 mb-4 mt-4">
                <li class="flex items-center justify-between">
                    <span class="text-sm font-medium font-rubik capitalize leading-6 text-[#2E2F38]">
                        {{ $t("label.total") }}
                    </span>
                    <span class="text-sm font-medium font-rubik capitalize leading-6 text-[#2E2F38]">
                        {{
                            currencyFormat((subtotal * cartDeliveryDays) +
                                checkoutProps.form.delivery_charge + (totalTax * cartDeliveryDays),
                                setting.site_digit_after_decimal_point,
                                setting.site_default_currency_symbol,
                                setting.site_currency_position)
                        }}
                    </span>
                </li>
            </ul>
            <div class="flex items-center justify-center gap-6" v-if="carts.length > 0">
                <button @click.prevent="resetCart"
                    class="capitalize text-sm font-medium leading-6 font-rubik w-full text-center rounded-3xl py-2 text-white bg-[#FB4E4E]">
                    {{ $t('button.cancel') }}
                </button>
                <button @click.prevent="orderSubmit"
                    class="capitalize text-sm font-medium leading-6 font-rubik w-full text-center rounded-3xl py-2 text-white bg-[#1AB759]">
                    {{ $t('button.order') }}
                </button>
            </div>
        </div>
    </div>


    <!--====================================
        ADD CUSTOMER MODAL PART START
=====================================-->
    <CustomerCreateComponent :props="customerProps" v-model:customerId="checkoutProps.form.customer_id" />
    <!--====================================
          ADD CUSTOMER MODAL PART END
    =====================================-->

    <!--====================================
      PAYMENT MODAL PART START
  =====================================-->
    <PaymentComponent :props="checkoutProps" />
    <!--====================================
          PAYMENT MODAL PART END
      =====================================-->


    <!--====================================
      ADDRESS MODAL PART START
  =====================================-->
    <CreateCustomerAddressComponent :props="address" v-model:areaId="checkoutProps.form.area_id" />
    <!--====================================
          ADDRESS MODAL PART END
      =====================================-->
    <!--====================================
      ADDRESS MODAL PART START
  =====================================-->
    <div id="datesModal" class="modal">
        <div class="modal-dialog">
            <div class="modal-header">
                <h3 class="modal-title">{{ $t("label.select_dates") }}</h3>
                <button class="close-modal lab-close-circle-line text-negative text-base"
                    @click="resetDatesModal"></button>
            </div>
            <div class="modal-body">
                <div class="rounded-2xl bg-white checkout">
                    <VueDatePicker v-model="delivery_dates" @update:model-value="handleDate"
                        @internal-model-change="handleDate" :disabled-dates="[new Date()]"
                        format="MM/dd/yyyy-MM/dd/yyyy" :selectForward="true" :time-picker-inline="false"
                        :enable-time-picker="false" :min-date="new Date()" :max-date="calculateMaxDate()"
                        :month-change-on-scroll="false" inline auto-apply multi-dates :disabled="!cartDeliveryDays">
                    </VueDatePicker>
                </div>
            </div>
        </div>
    </div>
    <!--====================================
          ADDRESS MODAL PART END
      =====================================-->


    <button @click="openCanvas('pos-cart')" type="button"
        class="db-pos-cartBtn fixed md:hidden bottom-0 z-10 left-0 w-full h-14 py-4 text-center flex items-center justify-center shadow-xl-top gap-3 bg-primary">
        <i class="lab lab-bag-2 lab-font-size-13 text-white"></i>
        <span class="text-base font-medium font-rubik text-white">
            {{ totalItems() }} {{ $t('label.items') }} - {{
                currencyFormat(subtotal,
                    setting.site_digit_after_decimal_point, setting.site_default_currency_symbol,
                    setting.site_currency_position)
            }}
        </span>
    </button>
</template>
<script>
import LoadingComponent from "../components/LoadingComponent.vue";
import ItemComponent from "./ItemComponent.vue";
import sourceEnum from "../../../enums/modules/sourceEnum";
import orderTypeEnum from "../../../enums/modules/orderTypeEnum";
import statusEnum from "../../../enums/modules/statusEnum";
import appService from "../../../services/appService";
import displayModeEnum from "../../../enums/modules/displayModeEnum";
import alertService from "../../../services/alertService";
import PaymentComponent from "./PaymentComponent.vue";
import posPaymentMethodEnum from "../../../enums/modules/posPaymentMethodEnum";
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';
import CreateCustomerAddressComponent from "./CreateCustomerAddressComponent.vue";
import CustomerCreateComponent from "./CustomerCreateComponent.vue";
import labelEnum from "../../../enums/modules/labelEnum";
import { useItemStore } from "../../../stores/item";
import { usePosCategoryStore } from "../../../stores/posCategory";
import { useUserStore } from "../../../stores/user";
import { useFrontendSettingStore } from "../../../stores/frontend/frontendSetting";
import { useFrontendLanguageStore } from "../../../stores/frontend/frontendLanguage";
import { usePosCartStore } from "../../../stores/posCart";
import { useFrontendCountryCodeStore } from "../../../stores/frontend/frontendCountryCode";
import { useGlobalStateStore } from "../../../stores/globalState";
import { useDeliveryDaysStore } from "../../../stores/deliveryDays";
import VueDatePicker from '@vuepic/vue-datepicker';
import '@vuepic/vue-datepicker/dist/main.css'
import { useFrontendDeliveryAreaStore } from "../../../stores/frontend/frontendDeliveryArea";
import _ from "lodash";

export default {
    name: "PosComponent",
    components: {
        CreateCustomerAddressComponent,
        LoadingComponent,
        ItemComponent,
        Swiper,
        SwiperSlide,
        PaymentComponent,
        VueDatePicker,
        CustomerCreateComponent
    },
    data() {
        return {
            loading: {
                isActive: false,
            },
            order: {},
            checkoutProps: {
                form: {
                    subtotal: 0,
                    cart_total: 0,
                    discount: 0,
                    delivery_charge: 0,
                    total: 0,
                    total_tax: 0,
                    area_id: null,
                    order_type: orderTypeEnum.DELIVERY,
                    number_of_days: null,
                    delivery_dates: [],
                    meal_types: [],
                    items: [],
                    source: sourceEnum.POS,
                    pos_payment_note: '',
                    pos_payment_method: posPaymentMethodEnum.CASH,
                    pos_received_amount: null,
                    customer_id: null,
                }
            },
            props: {
                search: {
                    paginate: 0,
                    order_column: "id",
                    order_type: "asc",
                    name: "",
                    item_category_id: "",
                    status: statusEnum.ACTIVE
                },
            },
            categoryProps: {
                paginate: 0,
                order_column: 'sort',
                order_type: 'asc',
                status: statusEnum.ACTIVE
            },

            statusEnum: statusEnum,
            posPaymentMethodEnum: posPaymentMethodEnum,
            customerProps: {
                form: {
                    name: "",
                    email: "",
                    phone: "",
                    password: "123456",
                    password_confirmation: "123456",
                    country_code: "",
                    status: statusEnum.ACTIVE,
                },
                search: {
                    paginate: 0,
                    order_column: "id",
                    order_type: "asc",
                    status: statusEnum.ACTIVE
                },
            },
            errors: {},
            address: {
                form: {
                    name: "",
                    address: "",
                    area_id: null,
                    country_code: "",
                    phone: "",
                    user_id: null,
                },
                flag: ""
            },
            selectedAddress: {},
            searchProps: {
                paginate: 0,
                order_column: 'id',
                order_type: 'asc',
                status: statusEnum.ACTIVE
            },
            item_category_id: "",
            delivery_dates: [],
            delivery_charge: 0,
            itemStore: useItemStore(),
            posCategoryStore: usePosCategoryStore(),
            frontendSettingStore: useFrontendSettingStore(),
            userStore: useUserStore(),
            frontendLanguageStore: useFrontendLanguageStore(),
            posCartStore: usePosCartStore(),
            frontendCountryCodeStore: useFrontendCountryCodeStore(),
            globalStateStore: useGlobalStateStore(),
            deliveryDaysStore: useDeliveryDaysStore(),
            frontendDeliveryAreaStore: useFrontendDeliveryAreaStore(),

        }
    },
    computed: {
        setting: function () {
            return this.frontendSettingStore.lists;
        },
        categories: function () {
            return this.posCategoryStore.lists;
        },
        items: function () {
            return this.itemStore.lists;
        },
        customers: function () {
            return this.userStore.lists;
        },
        carts: function () {
            return this.posCartStore.lists;
        },
        subtotal: function () {
            return this.posCartStore.subtotal;
        },
        direction: function () {
            return this.frontendLanguageStore.show.display_mode === displayModeEnum.RTL ? 'rtl' : 'ltr';
        },
        customerAddress: function () {
            return this.userStore.addressList;
        },
        deliveryDays: function () {
            return this.deliveryDaysStore.lists;
        },
        cartDeliveryDays: function () {
            return this.posCartStore.deliveryDays;
        },
        deliveryDates: function () {
            return this.posCartStore.deliveryDates;
        },
        groupedDates() {
            const months = [
                'January', 'February', 'March', 'April', 'May', 'June', 'July',
                'August', 'September', 'October', 'November', 'December'
            ];
            this.deliveryDates.sort((a, b) => new Date(a) - new Date(b));

            return this.deliveryDates.reduce((grouped, dateStr) => {
                const date = new Date(dateStr);
                const monthYear = `${months[date.getMonth()]}, ${date.getFullYear()}`;

                if (!grouped[monthYear]) {
                    grouped[monthYear] = [];
                }

                grouped[monthYear].push(dateStr);
                return grouped;
            }, {});
        },
        cartMealTypes: function () {
            return this.posCartStore.mealTypes;
        },
        cartDeliveryDates: function () {
            return this.posCartStore.deliveryDates;
        },
        totalTax: function () {
            return this.posCartStore.totalTax;
        }
    },
    mounted() {
        this.closeSidebar();
        this.itemCategories();
        this.itemList();
        this.selectCustomer();
        this.loading.isActive = true;
        this.deliveryDaysStore.fetchLists(this.searchProps).then(res => {
            this.loading.isActive = false;
        }).catch((err) => {
            this.loading.isActive = false;
        });

        this.frontendSettingStore.fetchLists().then(res => {
            this.frontendCountryCodeStore.fetchShow(res.data.data.company_country_code).then(countryCodeRes => {
                this.checkoutProps.form.country_code = countryCodeRes.data.data.calling_code;
                this.customerProps.form.country_code = countryCodeRes.data.data.calling_code;
                this.customerProps.flag = countryCodeRes.data.data.flag_emoji;
                this.address.flag = countryCodeRes.data.data.flag_emoji;
                this.address.form.country_code = countryCodeRes.data.data.calling_code;
                this.loading.isActive = false;
            }).catch((err) => {
                this.loading.isActive = false;
            });
            this.loading.isActive = false;
        }).catch((err) => {
            this.loading.isActive = false;
        });

        this.frontendDeliveryAreaStore.fetchLists({
            order_column: 'id',
            order_type: 'asc',
            status: statusEnum.ACTIVE,
        }).then(res => {
            this.loading.isActive = false;
        }).catch((err) => {
            this.loading.isActive = false;
        });

        if (this.posCartStore.deliveryDates && this.posCartStore.deliveryDates.length > 0) {
            this.delivery_dates = this.posCartStore.deliveryDates;
        }
        this.loading.isActive = false;
    },
    methods: {
        onlyNumber: function (e) {
            return appService.onlyNumber(e);
        },
        floatNumber: function (e) {
            return appService.floatNumber(e);
        },
        currencyFormat: function (amount, decimal, currency, position) {
            return appService.currencyFormat(amount, decimal, currency, position);
        },
        textShortener: function (text, number = 30) {
            return appService.textShortener(text, number);
        },
        openCanvas: function (id) {
            return appService.openCanvas(id);
        },
        closeCanvas: function (id) {
            return appService.closeCanvas(id);
        },
        search: function () {
            if (this.props.search.name) {
                this.props.search.item_category_id = "";
            } else {
                this.props.search.item_category_id = this.item_category_id;
            }
            this.itemList();

        },
        closeSidebar: function () {
            this.globalStateStore.set({ topSidebar: false });
            document?.querySelector(".db-sidebar")?.classList?.add("active");
            document?.querySelector(".db-main")?.classList?.add("expand");
        },
        updateDeliveryDays: function (e, day) {
            if (this.cartDeliveryDays !== day) {
                this.posCartStore.updateDeliveryDays(day);
                this.delivery_dates = [];
                this.posCartStore.updateDeliveryDates(this.delivery_dates);
            }
            this.deliveryChargeCalculation(this.checkoutProps.form.area_id);
        },
        handleDate: function (dates) {
            if (this.cartDeliveryDays > 0) {
                if (dates && dates.length > this.cartDeliveryDays) {
                    this.delivery_dates.pop();
                    alertService.info(this.$t('message.date_selection_limit_exceeded'));
                }
                this.posCartStore.updateDeliveryDates(this.delivery_dates);
            } else {
                this.delivery_dates = [];
            }
        },
        calculateMaxDate() {
            const duration = this.setting.site_order_accept_duration;
            const today = new Date();
            const maxDate = new Date(today);
            maxDate.setDate(today.getDate() + +duration);
            return maxDate;
        },
        openDatesModal: function () {
            appService.modalShow('#datesModal');
        },
        resetDatesModal: function () {
            appService.modalHide('#datesModal');
        },
        itemCategories: function (page = 1) {
            this.loading.isActive = true;
            this.props.search.page = page;
            this.posCategoryStore.fetchLists(this.categoryProps).then((res) => {
                if (!this.props.search.item_category_id) {
                    this.setCategory(res.data.data[0].id);
                    this.item_category_id = res.data.data[0].id;
                }
                this.loading.isActive = false;
            }).catch((err) => {
                this.loading.isActive = false;
            });
        },
        itemList: function (page = 1) {
            this.loading.isActive = true;
            this.props.search.page = page;
            this.itemStore.fetchLists(this.props.search).then((res) => {
                this.loading.isActive = false;
            }).catch((err) => {
                this.loading.isActive = false;
            });
        },
        selectCustomer: function () {
            this.loading.isActive = true;
            this.userStore.fetchLists({
                order_column: 'id',
                order_type: 'asc',
                status: statusEnum.ACTIVE,
            }).then((res) => {
                this.checkoutProps.form.customer_id = res.data.data[1].id;
                this.address.form.user_id = res.data.data[1].id;
                this.loading.isActive = false;
            }).catch((err) => {
                this.loading.isActive = false;
            });
        },
        setCategory: function (id) {
            this.props.search.item_category_id = id;
            this.itemList();
        },
        cartQuantityUp: function (id, e) {
            if (e.target.value > 0) {
                this.posCartStore.quantity({ id: id, status: e.target.value });
            }
        },
        cartQuantityIncrement: function (id) {
            this.posCartStore.quantity({ id: id, status: "increment" });
        },
        cartQuantityDecrement: function (id) {
            this.posCartStore.quantity({ id: id, status: "decrement" });
        },
        deleteCartItem: function (id) {
            this.posCartStore.deleteCartItem({ id: id, status: "decrement" });
        },
        resetCart: function () {
            this.posCartStore.resetCart();
        },
        orderSubmit: function () {
            this.loading.isActive = true;
            this.checkoutProps.form.cart_total = this.subtotal;
            this.checkoutProps.form.subtotal = parseFloat(this.subtotal * this.cartDeliveryDays);
            this.checkoutProps.form.delivery_dates = JSON.stringify(this.cartDeliveryDates);
            this.checkoutProps.form.meal_types = JSON.stringify(this.cartMealTypes);
            this.checkoutProps.form.number_of_days = this.cartDeliveryDays;
            this.checkoutProps.form.total_tax = (this.totalTax * this.cartDeliveryDays);
            this.checkoutProps.form.total = parseFloat((this.subtotal * this.cartDeliveryDays) + this.checkoutProps.form.delivery_charge + this.checkoutProps.form.total_tax).toFixed(this.setting.site_digit_after_decimal_point);
            this.checkoutProps.form.items = [];
            _.forEach(this.carts, (item, index) => {
                let item_variations = [];
                if (Object.keys(item.item_variations.variations).length > 0) {
                    _.forEach(item.item_variations.variations, (value, index) => {
                        item_variations.push({
                            "id": value,
                            "item_id": item.item_id,
                            "item_attribute_id": index,
                        });
                    });
                }

                if (Object.keys(item.item_variations.names).length > 0) {
                    let i = 0;
                    _.forEach(item.item_variations.names, (value, index) => {
                        item_variations[i].variation_name = index;
                        item_variations[i].name = value;
                        i++;
                    });
                }

                this.checkoutProps.form.items.push({
                    item_id: item.item_id,
                    item_price: item.convert_price,
                    instruction: item.instruction,
                    quantity: item.quantity,
                    discount: item.discount,
                    total_price: item.total,
                    item_variation_total: item.item_variation_total,
                    item_variations: item_variations,
                    taxes: item.taxes,
                    item_category: item.item_category
                });
            });
            this.checkoutProps.form.items = JSON.stringify(this.checkoutProps.form.items);
            this.loading.isActive = false;

            if (this.cartDeliveryDays === 0) {
                return alertService.info(this.$t('message.select_days'));
            }

            if (this.cartDeliveryDates.length !== this.cartDeliveryDays) {
                return alertService.info(this.$t('message.select_all_delivery_dates') + ' ' + this.cartDeliveryDays + ' ' + this.$t('label.days'));
            }
            if (!this.checkoutProps.form.area_id) {
                return alertService.error(this.$t("message.address_field_required"));
            }
            appService.modalShow('#orderpayment');
        },
        totalItems: function () {
            if (this.carts.length > 0) {
                let totalItem = 0;
                this.carts.forEach(cart => {
                    totalItem += cart.quantity;
                });
                return totalItem;
            }
        },
        addCustomers: function () {
            appService.modalShow("#addCustomer");
        },

        deliveryOrder: function () {
            this.$refs.deliveryOrderLabel.classList.add('active');
            this.$refs.deliveryOrderDiv.classList.add('block');
            this.$refs.deliveryOrderDiv.classList.remove('hidden');
        },
        gettingUserAddress: function (userId) {
            if (userId) {
                this.userStore.fetchAddressLists({ id: userId }).then(res => {
                    this.checkoutProps.form.area_id = res.data.data.area_id;
                    this.deliveryChargeCalculation(res.data.data.area_id);

                    this.loading.isActive = false;
                }).catch((err) => {
                    this.loading.isActive = false;
                });
            } else {
                this.checkoutProps.form.area_id = null;
                this.delivery_charge = 0;
                this.checkoutProps.form.delivery_charge = 0;
            }

        },
        openAddressModal: function () {
            appService.modalShow('#addressModal');
        },
        editAddressModal: function (address) {
            appService.modalShow("#addressModal");
            this.loading.isActive = true;
            this.userStore.setTemp(address.id);
            this.address.form.name = address.name;
            this.address.form.address = address.address;
            this.address.form.area_id = address.area_id;
            this.address.form.phone = address.phone;
            this.address.form.user_id = address.user_id;
            this.checkoutProps.form.area = null;
            this.loading.isActive = false;
        },
        deliveryChargeCalculation: function (id) {
            if (id) {
                this.checkoutProps.form.area_id = id;
                this.frontendDeliveryAreaStore.fetchShow(id).then(res => {
                    this.delivery_charge = parseFloat((res.data.data.convert_delivery_charge * this.cartMealTypes.length) * this.cartDeliveryDays);
                    this.checkoutProps.form.delivery_charge = this.delivery_charge;
                }).catch();

            } else {
                this.checkoutProps.form.area_id = null;
                this.delivery_charge = 0;
                this.checkoutProps.form.delivery_charge = 0;
            }
        },
    },
    watch: {
        "customerProps.form.password"(newValue) {
            this.customerProps.form.password_confirmation = newValue;
        },

        "checkoutProps.form.customer_id"(newValue) {
            this.gettingUserAddress(newValue);
        },
        "checkoutProps.form.area_id"(newValue) {
            this.deliveryChargeCalculation(newValue);

        },
        carts: {
            deep: true,
            handler(cartObject) {
                if (this.carts.length == 0) {
                    this.delivery_dates = [];
                    this.delivery_charge = 0;
                    this.selectCustomer();

                }
                this.deliveryChargeCalculation(this.checkoutProps.form.area_id);

            }
        }
    },
}
</script>