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

    <section class="container pt-[86px] max-w-[934px] w-full">
        <router-link :to="{ name: 'frontend.home' }" class="mb-3 inline-flex items-center gap-2 text-primary">
            <i class="lab lab-undo lab-font-size-16 text-base"></i>
            <span class="text-xs font-medium leading-6">{{ $t('label.back_to_home') }}</span>
        </router-link>
        <div class="row">
            <div class="col-12 md:col-7">
                <div class="p-4 rounded-2xl shadow-card bg-white mb-6">
                    <h2
                        class="capitalize mb-4 ltr:text-left rtl:text-right text-base font-medium leading-6 text-heading">
                        {{ $t('label.delivery_address') }}</h2>
                    <form>
                        <div class="row">
                            <div class="col-12">
                                <label class="text-xs capitalize mb-1 text-heading" for="name">{{
                                    $t('label.house_office_name')
                                    }}</label>
                                <input type="text" v-model="checkoutProps.form.name" id="name"
                                    v-bind:class="errors.name ? 'invalid' : ''"
                                    class="w-full h-12 text-sm rounded-lg border px-4 text-heading border-[#D9DBE9]">
                                <small class="db-field-alert" v-if="errors.name">{{ errors.name[0] }}</small>
                            </div>
                            <div class="col-12">
                                <label class="text-xs capitalize mb-1 text-heading" for="address">{{
                                    $t('label.full_address')
                                }}</label>
                                <input type="text" v-model="checkoutProps.form.address" id="address"
                                    v-bind:class="errors.address ? 'invalid' : ''"
                                    class="w-full h-12 text-sm rounded-lg border px-4 text-heading border-[#D9DBE9]">
                                <small class="db-field-alert" v-if="errors.address">{{ errors.address[0] }}</small>
                            </div>
                            <div class="col-12 sm:col-6">
                                <label class="text-xs capitalize mb-1 text-heading" for="area">{{ $t('label.area')
                                    }}</label>
                                <vue-select v-bind:class="errors.area_id ? 'invalid' : ''"
                                    class="w-full h-12 text-sm rounded-lg border px-4 text-heading border-[#D9DBE9] f-b-custom-select"
                                    id="area" @update:modelValue="deliveryChargeCalculation"
                                    v-model="checkoutProps.form.area" :options="deliveryAreas" label-by="name"
                                    value-by="id" :closeOnSelect="true" :searchable="true" :clearOnClose="true"
                                    placeholder="--" search-placeholder="--" />
                                <small class="db-field-alert" v-if="errors.area">{{ errors.area[0] }}</small>
                            </div>
                            <div class="col-12 sm:col-6">
                                <label class="text-xs capitalize mb-1 text-heading" for="phone">{{
                                    $t('label.phone_number')
                                }}</label>

                                <div class="col-12 w-full h-12 rounded-lg border px-4 flex items-center border-[#D9DBE9]"
                                    v-bind:class="errors.phone ? 'invalid' : ''">
                                    <div class="w-fit flex-shrink-0 dropdown-group">
                                        <button type="button" class="flex items-center gap-1 dropdown-btn">
                                            {{ flag }}
                                            <span class="whitespace-nowrap flex-shrink-0 text-xs">
                                                {{ checkoutProps.form.country_code }}
                                            </span>
                                            <input type="hidden" v-model="checkoutProps.form.country_code">
                                        </button>
                                    </div>
                                    <input id="phone" type="text" v-on:keypress="phoneNumber($event)"
                                        v-model="checkoutProps.form.phone"
                                        class="pl-4 text-sm w-full h-full text-heading">
                                </div>
                                <small class="db-field-alert" v-if="errors.phone">{{ errors.phone[0] }}</small>
                            </div>

                        </div>
                    </form>
                </div>
                <div class="row">
                    <div class="col-12 sm:col-4">
                        <div class="p-4 rounded-2xl shadow-card bg-white">
                            <h2
                                class="capitalize mb-2 ltr:text-left rtl:text-right text-base font-medium leading-6 text-heading">
                                {{ $t('label.select_days')
                                }}</h2>
                            <div class="dayslider">
                                <Swiper dir="ltr" v-if="deliveryDays.length > 0" :speed="1000" slidesPerView="auto"
                                    :spaceBetween="16" class="flex sm:flex-col flex-row flex-nowrap">
                                    <SwiperSlide v-for="deliveryDay in deliveryDays" :key="deliveryDay"
                                        class="!w-fit sm:!w-full !h-12 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>
                    <div class="col-12 sm:col-8 mb-12">
                        <div class="rounded-2xl shadow-card bg-white checkout">
                            <label
                                class="text-base leading-6 block font-medium capitalize text-heading p-4 pb-0 ltr:pr-0 rtl:pl-0 mb-4">
                                {{ $t('label.select_dates') }}</label>
                            <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>
            <div class="col-12 md:col-5 mb-20">
                <div class="rounded-2xl shadow-card bg-white">
                    <div class="p-4 border-b">
                        <h3 class="capitalize font-medium mb-3 text-center">{{
                            $t('label.cart_summary')
                            }}</h3>
                        <div class="pl-3">
                            <div v-for="cart in carts"
                                class="mb-3 pb-3 border-b last:mb-0 last:pb-0 last:border-b-0 border-gray-2">
                                <div class="flex items-start gap-3 relative">
                                    <h3
                                        class="absolute top-5 ltr:-left-3 rtl:-right-3 text-sm w-[26px] h-[26px] leading-[26px] text-center rounded-full text-white bg-black">
                                        {{ cart.quantity }}</h3>
                                    <img class="w-16 h-16 rounded-lg flex-shrink-0" :src="cart.image" alt="thumbnail">
                                    <div class="w-full">
                                        <p
                                            class="w-fit text-[10px] font-medium leading-5 px-2 rounded-full text-[#008BBA] bg-[#E0F8FF]">
                                            {{ cart.item_category.name }}</p>
                                        <span class="text-sm font-medium capitalize transition text-heading">
                                            {{ textShortener(cart.name, 25) }}
                                        </span>
                                        <p v-if="Object.keys(cart.item_variations.variations).length !== 0"
                                            class="capitalize text-xs mb-1.5">
                                            <span
                                                v-for="(variation, variationName, index) in cart.item_variations.names">
                                                {{ variationName }}: {{ variation }}
                                                <span
                                                    v-if="index + 1 < Object.keys(cart.item_variations.names).length">,
                                                    &nbsp;</span>
                                            </span>
                                        </p>
                                        <h4 class="text-xs font-semibold">
                                            {{
                                                currencyFormat(cart.total, setting.site_digit_after_decimal_point,
                                                    setting.site_default_currency_symbol,
                                                    setting.site_currency_position)
                                            }}
                                        </h4>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="p-4">
                        <div class="rounded-xl mb-6 border border-[#EFF0F6]">
                            <ul class="flex flex-col gap-2 p-3 border-b border-dashed border-[#EFF0F6]">
                                <li class="flex items-center justify-between text-heading">
                                    <span class="text-sm leading-6 capitalize">{{ $t('label.cart_total') }}</span>
                                    <span class="text-sm leading-6 capitalize">{{
                                        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 text-heading">
                                    <span class="text-sm leading-6 capitalize">{{ $t('label.no_of_days') }}</span>
                                    <span class="text-sm leading-6 capitalize">{{ cartDeliveryDays }}</span>
                                </li>
                            </ul>
                            <ul class="flex flex-col gap-2 p-3 border-b border-dashed border-[#EFF0F6]">
                                <li class="flex items-center justify-between text-heading">
                                    <span class="text-sm leading-6 capitalize">{{ $t('label.subtotal') }}</span>
                                    <span class="text-sm leading-6 capitalize">{{
                                        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 text-heading">
                                    <span class="text-sm leading-6 capitalize">{{ $t('label.tax') }}</span>
                                    <span class="text-sm leading-6 capitalize">{{
                                        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 text-heading">
                                    <span class="text-sm leading-6 capitalize">{{ $t('label.delivery_charge') }}</span>
                                    <span class="text-sm leading-6 capitalize 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>
                            <div class="flex items-center justify-between p-3">
                                <h4 class="text-sm leading-6 font-semibold capitalize">{{ $t('label.total') }}
                                </h4>
                                <h5 class="text-sm leading-6 font-semibold capitalize">{{
                                    currencyFormat((subtotal * cartDeliveryDays) +
                                        checkoutProps.form.delivery_charge + (totalTax * cartDeliveryDays),
                                        setting.site_digit_after_decimal_point,
                                        setting.site_default_currency_symbol,
                                        setting.site_currency_position)
                                }}</h5>
                            </div>
                        </div>
                        <button type="button"
                            v-if="carts.length > 0 && (setting.site_cash_on_delivery == activityEnum.ENABLE || setting.site_online_payment_gateway == activityEnum.ENABLE)"
                            class="w-full rounded-3xl capitalize font-medium leading-6 py-3 text-white bg-primary"
                            @click="orderSubmit">
                            {{ $t('button.place_order') }}</button>
                        <p v-if="setting.site_cash_on_delivery == activityEnum.DISABLE && setting.site_online_payment_gateway == activityEnum.DISABLE"
                            class="text-sm text-primary text-center">{{ $t('message.payment_option_disable')
                            }}</p>
                    </div>
                </div>
            </div>
        </div>
    </section>
</template>
<script>
import appService from "../../../services/appService";
import alertService from "../../../services/alertService";
import LoadingComponent from "../components/LoadingComponent.vue";
import router from "../../../router";
import _ from "lodash";
import sourceEnum from "../../../enums/modules/sourceEnum";
import statusEnum from "../../../enums/modules/statusEnum";
import activityEnum from "../../../enums/modules/activityEnum";
import orderTypeEnum from "../../../enums/modules/orderTypeEnum";
import { useFrontendSettingStore } from "../../../stores/frontend/frontendSetting";
import { useFrontendCartStore } from "../../../stores/frontend/frontendCart";
import { useFrontendDeliveryDaysStore } from "../../../stores/frontend/frontendDeliveryDays";
import { useFrontendDeliveryAreaStore } from "../../../stores/frontend/frontendDeliveryArea";
import { useFrontendOrderStore } from "../../../stores/frontend/frontendOrder";
import { useFrontendCountryCodeStore } from "../../../stores/frontend/frontendCountryCode";
import { useFrontendAddressStore } from "../../../stores/frontend/frontendAddress";
import { useAuthStore } from "../../../stores/auth";
import VueDatePicker from '@vuepic/vue-datepicker';
import '@vuepic/vue-datepicker/dist/main.css'
import "swiper/css"
import { Swiper, SwiperSlide } from "swiper/vue";


export default {
    name: "CheckoutComponent",
    components: {
        LoadingComponent,
        VueDatePicker,
        Swiper,
        SwiperSlide
    },
    data() {
        return {
            loading: {
                isActive: false,
            },
            checkoutProps: {
                form: {
                    subtotal: 0,
                    cart_total: 0,
                    discount: 0,
                    delivery_charge: 0,
                    total: 0,
                    total_tax: 0,
                    source: sourceEnum.WEB,
                    name: "",
                    address: "",
                    country_code: "",
                    phone: "",
                    area: null,
                    order_type: orderTypeEnum.DELIVERY,
                    number_of_days: null,
                    delivery_dates: [],
                    meal_types: [],
                    items: []
                }
            },
            activityEnum: activityEnum,
            delivery_dates: [],
            delivery_charge: 0,
            search: {
                paginate: 0,
                order_column: 'id',
                order_type: 'asc',
                status: statusEnum.ACTIVE
            },
            flag: "",
            errors: {},
            frontendSettingStore: useFrontendSettingStore(),
            frontendCartStore: useFrontendCartStore(),
            frontendDeliveryDaysStore: useFrontendDeliveryDaysStore(),
            frontendDeliveryAreaStore: useFrontendDeliveryAreaStore(),
            frontendOrderStore: useFrontendOrderStore(),
            frontendCountryCodeStore: useFrontendCountryCodeStore(),
            frontendAddressStore: useFrontendAddressStore(),
            authStore: useAuthStore(),
        }
    },
    computed: {
        setting: function () {
            return this.frontendSettingStore.lists;
        },
        countryCode: function () {
            return this.frontendCountryCodeStore.show;
        },
        carts: function () {
            return this.frontendCartStore.lists;
        },
        subtotal: function () {
            return this.frontendCartStore.subtotal;
        },
        deliveryDays: function () {
            return this.frontendDeliveryDaysStore.lists;
        },
        cartDeliveryDays: function () {
            return this.frontendCartStore.deliveryDays;
        },
        deliveryAreas: function () {
            return this.frontendDeliveryAreaStore.lists;
        },
        cartMealTypes: function () {
            return this.frontendCartStore.mealTypes;
        },
        cartDeliveryDates: function () {
            return this.frontendCartStore.deliveryDates;
        },
        totalTax: function () {
            return this.frontendCartStore.totalTax;
        }
    },
    mounted() {
        this.loading.isActive = true;
        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.flag = countryCodeRes.data.data.flag_emoji;
                this.loading.isActive = false;
            }).catch((err) => {
                this.loading.isActive = false;
            });
            this.loading.isActive = false;
        }).catch((err) => {
            this.loading.isActive = false;
        });
        this.frontendDeliveryDaysStore.fetchLists(this.search).then(res => {
            this.loading.isActive = false;
        }).catch((err) => {
            this.loading.isActive = false;
        });

        this.frontendDeliveryAreaStore.fetchLists(this.search).then(res => {
            this.loading.isActive = false;
        }).catch((err) => {
            this.loading.isActive = false;
        });
        this.frontendAddressStore.fetchLists().then(res => {
            this.checkoutProps.form.name = res.data.data.name;
            this.checkoutProps.form.area = res.data.data.area_id;
            this.checkoutProps.form.address = res.data.data.address;
            this.checkoutProps.form.phone = res.data.data.phone;
            this.deliveryChargeCalculation(res.data.data.area_id);

            this.loading.isActive = false;
        }).catch((err) => {
            this.loading.isActive = false;
        });

        if (this.frontendCartStore.deliveryDates && this.frontendCartStore.deliveryDates.length > 0) {
            this.delivery_dates = this.frontendCartStore.deliveryDates;
        }

    },
    methods: {
        currencyFormat: function (amount, decimal, currency, position) {
            return appService.currencyFormat(amount, decimal, currency, position);
        },
        phoneNumber(e) {
            return appService.phoneNumber(e);
        },
        textShortener: function (text, number = 30) {
            return appService.textShortener(text, number);
        },
        updateDeliveryDays: function (e, day) {
            if (this.cartDeliveryDays !== day) {
                this.frontendCartStore.updateDeliveryDays(day);
                this.delivery_dates = [];
                this.frontendCartStore.updateDeliveryDates(this.delivery_dates);
            }
            this.deliveryChargeCalculation(this.checkoutProps.form.area);
        },
        updateAddress: function (areaId) {
            this.checkoutProps.form.area_id = areaId;
            this.deliveryChargeCalculation(areaId);
        },
        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.frontendCartStore.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;
        },
        deliveryChargeCalculation: function (id) {
            if (id) {
                this.checkoutProps.form.area = 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 = null;
                this.delivery_charge = 0;
                this.checkoutProps.form.delivery_charge = 0;
            }
        },
        orderSubmit: function () {

            if (this.cartDeliveryDates.length !== this.cartDeliveryDays && this.checkoutProps.form.name && this.checkoutProps.form.address && this.checkoutProps.form.area && this.checkoutProps.form.phone) {
                return alertService.error(this.$t('message.select_all_delivery_dates') + ' ' + this.cartDeliveryDays + ' ' + this.$t('label.days'));
            }

            if (this.cartDeliveryDays === 0 && this.checkoutProps.form.name && this.checkoutProps.form.address && this.checkoutProps.form.area && this.checkoutProps.form.phone) {
                return alertService.error(this.$t('message.select_days'));
            }
            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 > 0 ? this.cartDeliveryDays : null;
            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.frontendOrderStore.save(this.checkoutProps.form).then(orderResponse => {
                this.checkoutProps.form.subtotal = null;
                this.checkoutProps.form.discount = 0;
                this.checkoutProps.form.delivery_charge = 0;
                this.checkoutProps.form.total = 0;
                this.checkoutProps.form.total_tax = 0;
                this.checkoutProps.form.area = null;
                this.checkoutProps.form.number_of_days = null;
                this.checkoutProps.form.items = [];
                this.checkoutProps.form.meal_types = [];
                this.delivery_dates = [];
                this.frontendCartStore.resetCart();
                router.push({ name: "frontend.myOrder", query: { id: orderResponse.data.data.id } });

                if (this.setting.site_cash_on_delivery == statusEnum.INACTIVE) {
                    window.location.href = '/payment/' + orderResponse.data.data.id + '/pay';
                } else {
                    router.push({ name: "frontend.myOrder", query: { id: orderResponse.data.data.id } });
                }
                this.loading.isActive = false;
                this.errors = {};
            }).catch((err) => {
                this.loading.isActive = false;
                this.errors = {};
                this.errors = err.response.data.errors;
                if (typeof err.response.data.errors === 'object' && !err.response.data.errors.name && !err.response.data.errors.address && !err.response.data.errors.area && !err.response.data.errors.phone) {
                    _.forEach(err.response.data.errors, (error) => {
                        alertService.error(error[0]);
                    });
                }
            });
        },
    },
    watch: {
        carts: {
            deep: true,
            handler(cartObject) {
                this.deliveryChargeCalculation(this.checkoutProps.form.area);
                if (this.carts.length == 0) {
                    this.delivery_dates = [];

                }

            }
        }
    }
}
</script>