<template>

    <div class="subscriptionItem" v-if="item && formUrl.length">

        <div class="subscriptionItem__loadingBox" v-if="loading">

            <loading-spinner
                    :loading="loading"
                    :show-loading-text="false"
                    loading-text="Updating subscription"
            ></loading-spinner>

        </div> <!-- .__loadingBox -->

        <div class="subscriptionItem__inner">

            <div class="subscriptionItem__title">

                <div
                        class="subscriptionItem__name"
                        v-html="productTitle"
                        v-if="productTitle.length"
                ></div> <!-- .subscriptionItem__name -->

                <div class="subscriptionItem__edit" v-if="subscriptionStatus !== 'cancelled'">

                    <button
                            type="button"
                            @click.prevent="toggleOptions"
                    >

                        <span class="visuallyHidden">Edit subscription item</span>

                        <i class="svgIcon">

                            <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    viewBox="0 0 512 512"
                                    width="16"
                                    height="16"
                            >
                                <path d="M471.6 21.7c-21.9-21.9-57.3-21.9-79.2 0L362.3 51.7l97.9 97.9 30.1-30.1c21.9-21.9 21.9-57.3 0-79.2L471.6 21.7zm-299.2 220c-6.1 6.1-10.8 13.6-13.5 21.9l-29.6 88.8c-2.9 8.6-.6 18.1 5.8 24.6s15.9 8.7 24.6 5.8l88.8-29.6c8.2-2.7 15.7-7.4 21.9-13.5L437.7 172.3 339.7 74.3 172.4 241.7zM96 64C43 64 0 107 0 160L0 416c0 53 43 96 96 96l256 0c53 0 96-43 96-96l0-96c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 96c0 17.7-14.3 32-32 32L96 448c-17.7 0-32-14.3-32-32l0-256c0-17.7 14.3-32 32-32l96 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L96 64z" fill="currentColor"/>
                            </svg>

                        </i>
                    </button>

                </div> <!-- .subscriptionItem__edit -->

            </div> <!-- .subscriptionItem__title -->

            <div class="subscriptionItem__options" v-if="optionsOpen">

                <product-size-select
                        :sizes="subscriptionSizes"
                        :selected-size-id="defaultSize"
                        select-label="Options"
                        :single-select="true"
                        :product-id="productID"
                        @sizechanged="updateSize"
                ></product-size-select>

            </div> <!-- .subscriptionItem__options -->

            <div class="subscriptionItem__pricing">
                <i class="fas fa-sync-alt subscriptionItem__pricingIcon"></i>
                <multi-currency-price :price="subscriptionPrice"/>
                <span class="subscriptionItem__pricingSep">/</span>
                <span class="subscriptionItem__pricingFreq" v-html="frequencyShort"></span>
            </div> <!-- .subscriptionItem__pricing -->

            <div class="subscriptionItem__buttons" v-if="optionsOpen">

                <button
                        type="button"
                        class="button"
                        @click.prevent="updateSubscription"
                >
                    Update
                </button>

                <button
                        type="button"
                        class="button buttonAlert"
                        @click.prevent="closeOptions(true)"
                >
                    Close
                </button>


            </div> <!-- .subscriptionItem__buttons -->

            <div
                    class="subscriptionItem__message"
                    v-if="message.length"
            >

                <div
                        :class="[hasError ? 'error' : 'success']"
                        v-text="message"
                ></div> <!-- .alert -->

            </div> <!-- .subscriptionItem__message -->

        </div> <!-- .subscriptionItem__inner -->

    </div> <!-- .subscriptionItem -->

</template>

<script>

import axios from 'axios';
import collect from "collect.js";
import productSizeSelect from '../../../../../../../../sites/default/js/components/shop/item/partials/product_size_select';

export default {

    components: {
        productSizeSelect
    },

    props: {

        formUrl: {
            type: [String],
            default() {
                return ''
            }
        },

        subscriptionId: {
            type: [String, Number],
            default() {
                return 0
            }
        },

        subscriptionStatus: {
            type: [String],
            default() {
                return 'active'
            }
        },

        item: {
            type: [Object, Array, Boolean],
            default() {
                return false
            }
        }
    },

    data() {

        return {
            defaultSize: 0,
            selectedSize: 0,
            optionsOpen: false,
            timeout: null,
            loading: false,
            message: '',
            hasError: false
        }

    },

    created() {

        //Set initial size
        this.selectedSize = parseInt(this.item.shop_item_size_id);

        if(isNaN(this.selectedSize)) {
            this.selectedSize = 0;
        }

        //Set default selected size
        this.defaultSize = this.selectedSize;


    },

    computed: {


        productTitle() {

            const allSizes = collect(this.item.shop_item.sizes).toArray();

            const sizes = allSizes.filter(size => {

                const selectedID = parseInt(this.selectedSize);

                if(!isNaN(selectedID)) {

                    return selectedID == parseInt(size.id);
                }

            });

            if(sizes.length) {

                const size = sizes[0];

                return this.item.shop_item.name + ' (' + size.size + ')';


            }

            return '';

        },

        subscriptionSizes() {

            const allSizes = collect(this.item.shop_item.sizes).toArray();

            const sizes = allSizes.map(size => {

                if(typeof size.subscription_preference != 'undefined') {

                    if(size.subscription_preference?.is_allowed) {

                        size.price = size.subscription_preference.price;
                        size.price_exvat = size.subscription_preference.price_exvat;
                        size.sale_price = size.subscription_preference.sale_price;
                        size.sale_price_ex_vat = size.subscription_preference.sale_price_ex_vat;
                        size.price_per_pill = size.subscription_preference.price_per_pill;


                    }

                }

                return size;

            }).filter(size => size.subscription_preference?.is_allowed);

            return sizes;

        },

        productID() {
            return parseInt(this.item.shop_item.id);
        },

        subscriptionPrice() {

            let sizeSelected = this.item.shop_item.sizes.filter(size => size.id == this.selectedSize);

            if(sizeSelected.length) {
                sizeSelected = sizeSelected[0];

                let price = sizeSelected.subscription_preference.price;
                let salePrice = sizeSelected.subscription_preference.sale_price;

                if(salePrice < price && salePrice > 0 && price != salePrice) {
                    price = salePrice;
                }


                return price.toFixed(2);

            }

            return 0;
        },

        frequency() {

            let frequencyText = '';

            const selectedSize = this.getSize(this.selectedSize);

            if(selectedSize) {

                if(typeof selectedSize.subscription_preference != 'undefined') {

                    const prefs = selectedSize.subscription_preference;
                    const multiplier = parseInt(prefs.interval_multiplier);
                    let interval = prefs.interval;

                    if(!isNaN(multiplier) && interval.length) {

                        if(multiplier > 0) {

                            if (multiplier === 1 && interval == 'months') {
                                interval = 'month';
                            }else if(multiplier === 1 && interval == 'weeks') {
                                interval = 'week';
                            }else if(multiplier === 1 && interval == 'days') {
                                interval = 'day';
                            }

                            if(multiplier === 1) {
                                frequencyText = 'per ' + interval;
                            }else {
                                frequencyText = 'every ' + multiplier + ' ' + interval
                            }

                        }


                    }

                }

                return frequencyText;

            }

            return '';

        },

        frequencyShort() {
            const freq = this.frequency;
            if (freq.startsWith('per ')) {
                return freq.substring(4);
            }
            if (freq.startsWith('every ')) {
                return freq.substring(6);
            }
            return freq;
        }

    },

    methods: {

        updateSubscription() {

            const vm = this;
            this.loading = true;

            axios.post(vm.formUrl, {
                subscription_item_id: this.item.id,
                shop_item_id: this.item.shop_item_id,
                shop_item_size_id: vm.selectedSize

            })
            .then(function (response) {

                const data = response.data;
                const errors = data.errors;
                const message = data.message;

                if(errors) {
                    vm.showMessage(message, true);
                }else{
                    vm.defaultSize = vm.selectedSize;
                    vm.showMessage(message, false);
                }

            })
            .catch(function (error) {
                vm.showMessage('Un unexpected error occurred, please try again later', true);
            })
            .finally(function () {
                vm.loading = false;
                vm.closeOptions(false);
            });

        },

        getSize(id) {

            const allSizes = collect(this.item.shop_item.sizes).toArray();

           const sizes = allSizes.filter(size => {

               const sizeID = parseInt(size.id);
               const targetID = parseInt(id);

               if(sizeID == targetID && !isNaN(sizeID) && !isNaN(targetID)) {

                   return size;

               }

            });

           if(sizes.length) {
               return sizes[0];
           }

           return false;

        },

        updateSize(sizeID) {

            const selectedID = parseInt(sizeID);

            if(!isNaN(selectedID)) {
                this.selectedSize = selectedID;
            }

        },

        toggleOptions() {
            this.optionsOpen = !this.optionsOpen;

            if(!this.optionsOpen) {
                this.selectedSize = this.defaultSize;
            }else {
                this.message = '';
            }
        },

        closeOptions(reset) {

            this.optionsOpen = false;

            if(!this.optionsOpen && reset) {
                this.selectedSize = this.defaultSize;
            }

        },

        showMessage(message, hasError) {

            this.hasError = hasError;

            if(typeof hasError == 'undefined') {
                this.hasError = false;
            }

            this.message = message;


        }
    }

}
</script>

<style lang="less">


    .subscriptionItem {

        position: relative;
        .rems(16);
        line-height: 1.2em;

        &__loadingBox {

            position: absolute;
            z-index: 2;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            background: transparent;

            .loadingSpinner {
                height: 68px;
                margin-top: -30px;
            }

        }

        &__inner {
            position: relative;
            z-index: 1;
        }

        &__title {
            display: flex;
            gap: 0;
            flex-wrap: wrap;
            padding: 0 0 8px;
        }

        &__name {

            .rems(16);
            line-height: 1.2em;
            color: var(--text_color);

            font-weight: normal;
            max-width: ~"calc(100% - 38px)";

        }

        &__edit {

            position: relative;
            top: -8px;
            margin-bottom: -20px;

            button {
                width: 38px;
                height: 38px;
                padding: 4px;
                cursor: pointer;
                background: transparent;
                border: none;
                color: var(--secondary_color);
				opacity: 1;

                transition: color 200ms linear;
                outline: 0;

                &:hover, &:active, &:focus-visible {
                    color: var(--secondary_color);
					opacity: 0.8;
                    transition: color 200ms linear, opacity 200ms linear;
                }

                .svgIcon {
                    width: 16px;
                    height: 16px;
                }
            }
        }

        &__pricing {
            display: flex;
            align-items: baseline;
            gap: 4px;
            .rems(15);
            line-height: 24px;
        }

        &__pricingIcon {
            .rems(11);
            color: var(--highlight_color, #226B64);
            position: relative;
            top: -1px;
            margin-right: 2px;
        }

        &__pricingSep {
            .rems(14);
            color: var(--text_color, #333);
            opacity: 0.4;
        }

        &__pricingFreq {
            .rems(13);
            color: var(--text_color, #333);
            opacity: 0.6;
        }

        .multiPrice {
            .rems(16);
            line-height: 24px;
            font-weight: 600;
            flex: 0 0 auto;
            color: var(--primary_color);
        }

        &__options {

            padding: 8px 0 0;

            .productSizes {
                max-width: 450px;

                .multipleSelect {
                    gap: 16px;
                }
            }

        }

        &__buttons {

            padding: 16px 0 0;

            .button {

                margin: 0;
                .rems(14);
                line-height: 1.2em;
                padding: 8px 16px;


                & + .button {
                    margin-left: 4px;
                }

            }

        }

        &__message {

            padding: 16px 0 0;

            .success, .error {

                padding: 12px 16px;
                .rems(14);
                line-height: 1.2em;
                margin: 0;
                font-weight: 600;
            }

            .success {
                color: var(--success_color);

            }

            .error {
                color: var(--alert_color);

            }

        }


    }

</style>
