<template>
    <div class="row m-b-10 parentContainer">
        <div class="col">
            <div class="row align-items-center">
                <div class="col p-t-5 p-b-5">
                    <div class="col text-center">
                        <div class="row m-b-20">
                            <div class="col">
                                <h5 class="all-caps">Merge Transfers</h5>
                                <div class="fs-11">Are you sure you want to merge? This action is undoable.</div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col p-r-5">
                                <div data-dismiss="modal" class="btn btn-sm btn-default bg-master-lighter btn-block b-rad-none">Cancel</div>
                            </div>
                            <div class="col p-l-5">
                                <div data-dismiss="modal" class="btn btn-sm btn-success btn-block b-rad-none" @click="mergeTransfer()">Merge</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { getCurrentInstance } from 'vue';
import { useFormHandler } from '@/composables/useFormHandler';
import { useUiStore } from '@/stores/ui';
import route from '@/general/functions/router';

const { proxy } = getCurrentInstance() as any;

const props = defineProps<{
    section: string;
    booking: any;
    bookingToMerge: any[];
}>();

const { parameters, submit } = useFormHandler(props);
const uiStore = useUiStore();

const successHandler = () => {
    setTimeout(() => {
        window.location.href = route('booking.details', props.booking.marking);
    }, 2000);
};

const errorHandler = () => {
    // uiStore.toggleLoading(props.section, false);
    proxy.emitter.emit('setLoading', false);
};

const mergeTransfer = () => {
    // uiStore.toggleLoading(props.section, true);
    proxy.emitter.emit('setLoading', true);

    const bookings = props.bookingToMerge.map((booking: any) => booking.id);

    if (bookings.length > 0) {
        parameters.value = {
            id: props.booking.id,
            booking_ids: bookings
        };
        submit(route('api.booking.merge'), 'post', props.section, true, true, successHandler, errorHandler);
    } else {
        uiStore.toggleLoading(props.section, false);
    }
};
</script>
