<script setup>
    import AppLayout from "../../../../resources/js/layouts/AppLayout.vue";
    import {reactive, watch, ref, computed} from 'vue'
    import { subWeeks, format, parseISO, isValid, addDays } from 'date-fns'
    import ErrorText from "../../../Views/Components/ErrorText.vue";
    import {useAjax} from "../../../../resources/js/components/ajaxHandler.js";
    import ParticipationFees from "./Partials/ParticipationFees.vue";

    const { request } = useAjax();


    const props = defineProps({
        'emailAddress': String,
        'eventAccount': String,
        'eventIban': String,
        "eventPayPerDay": Boolean,
        "participationFeeType": String,
    })

    const errors = reactive({})

    const formData = reactive({
        eventName: '',
        eventPostalCode: '',
        eventLocation: '',
        eventEmail: props.emailAddress ? props.emailAddress : '',
        eventBegin: '',
        eventEnd: '',
        eventEarlyBirdEnd: '',
        eventEarlyBirdEndAmountIncrease: 50,
        eventRegistrationFinalEnd: '',
        eventAccount: props.eventAccount ? props.eventAccount : '',
        eventIban: props.eventIban ? props.eventIban : '',
        eventPayPerDay: props.eventPayPerDay ? props.eventPayPerDay : false,
        eventParticipationFeeType: props.participationFeeType ? props.participationFeeType : 'fixed',
    });

    watch(
        () => formData.eventBegin,
        (newValue) => {
            if (!newValue) return

            const beginDate = parseISO(newValue)

            if (!isValid(beginDate)) return

            const fourWeeksBefore = subWeeks(beginDate, 4)
            const twoWeeksBefore = subWeeks(beginDate, 2)
            const threeDaysAfter = addDays(beginDate, 2)

            formData.eventEarlyBirdEnd = format(
                fourWeeksBefore,
                'yyyy-MM-dd'
            )

            formData.eventRegistrationFinalEnd = format(
                twoWeeksBefore,
                'yyyy-MM-dd'
            )

            formData.eventEnd = format(
                threeDaysAfter,
                'yyyy-MM-dd'
            )
        }
    )

    const formIsValid = computed(() => {
        errors.eventEmail = '';
        errors.eventName = '';
        errors.eventLocation = '';
        errors.eventPostalCode = '';
        errors.eventBegin = '';
        errors.eventEnd = '';
        errors.eventEarlyBirdEnd = '';
        errors.eventRegistrationFinalEnd = '';
        errors.eventAccount = '';
        errors.eventIban = '';

        var returnValue = true;

        if (!formData.eventName) {
            errors.eventName = 'Bitte gib den Veranstaltungsnamen ein'
            returnValue = false
        }

        if (!formData.eventEmail) {
            errors.eventEmail = 'Bitte gib die E-Mail-Adresse der Veranstaltungsleitung für Rückfragen der Teilnehmenden ein'
            returnValue = false
        }

        if (!formData.eventLocation) {
            errors.eventLocation = 'Bitte gib den Veranstaltungsort ein'
            returnValue = false
        }

        if (!formData.eventPostalCode) {
            errors.eventPostalCode = 'Bitte gib die Postleitzahl des Veranstaltungsorts ein'
            returnValue = false
        }

        if (!formData.eventBegin) {
            errors.eventBegin = 'Bitte gib das Anfangsdatum der Veranstaltung ein'
            returnValue = false
        }

        if (!formData.eventEnd ||formData.eventEnd < formData.eventBegin ) {
            errors.eventEnd = 'Das Enddatum darf nicht vor dem Anfangsdatum liegen'
            returnValue = false
        }

        if (!formData.eventEarlyBirdEnd ||formData.eventEarlyBirdEnd > formData.eventBegin ) {
            errors.eventEarlyBirdEnd = 'Das Enddatum der Early-Bird-Phase muss vor dem Veranstaltungsbeginn liegen'
            returnValue = false
        }

        if (!formData.eventRegistrationFinalEnd ||formData.eventRegistrationFinalEnd > formData.eventBegin ) {
            errors.eventRegistrationFinalEnd = 'Der Anmeldeschluss darf nicht nach dem Veranstaltungsbeginn liegen'
            returnValue = false
        }

        if (!formData.eventAccount) {
            errors.eventAccount = 'Bitte gib an, auf wen das Veranstaltungskonto für eingehende Beiträge läuft'
            returnValue = false
        }

        if (!formData.eventIban) {
            errors.eventIban = 'Bitte gib die IBAN des Kontos für Teilnahmebeiträge ein'
            returnValue = false
        }

        return returnValue;

    })

    const showParticipationFees = ref(false)
    const newEvent = ref(null)

    async function createEvent() {
        if (!formIsValid.value) return false

        const data = await request("/api/v1/event/create", {
            method: "POST",
            body: {
                eventName: formData.eventName,
                eventPostalCode: formData.eventPostalCode,
                eventLocation: formData.eventLocation,
                eventEmail: formData.eventEmail,
                eventBegin: formData.eventBegin,
                eventEnd: formData.eventEnd,
                eventEarlyBirdEnd: formData.eventEarlyBirdEnd,
                eventEarlyBirdEndAmountIncrease: formData.eventEarlyBirdEndAmountIncrease,
                eventRegistrationFinalEnd: formData.eventRegistrationFinalEnd,
                eventAccount: formData.eventAccount,
                eventIban: formData.eventIban,
                eventPayPerDay: formData.eventPayPerDay,
                eventParticipationFeeType: formData.eventParticipationFeeType,
            }
        });

        if (data.status !== 'success') {
            toast.error(data.message);
            return false;
        } else {
            newEvent.value = data.event;
            showParticipationFees.value = true;
        }
    }

    async function finishCreation() {
        window.location.href = '/event/details/' + newEvent.value.identifier;
    }


</script>

<template>
    <AppLayout title="Neue Veranstaltung">
        <fieldset>
            <legend>
                <span style="font-weight: bolder;">Grundlegende Veranstaltungsdaten</span>
            </legend>
            <ParticipationFees v-if="showParticipationFees" :event="newEvent" @close="finishCreation" />

            <table style="margin-top: 40px; width: 100%" v-else>
                <tr style="vertical-align: top;">
                    <th class="width-medium pr-20 height-50">Veranstaltungsname</th>
                    <td class="height-50"><input type="text" v-model="formData.eventName" class="width-half-full" />
                    <ErrorText :message="errors.eventName" /></td>
                </tr>

                <tr style="vertical-align: top;">
                    <th class="width-medium pr-20 height-50">Veranstaltungsort</th>
                    <td class="height-50"><input type="text" v-model="formData.eventLocation" class="width-half-full" />
                        <ErrorText :message="errors.eventLocation" /></td>
                </tr>

                <tr style="vertical-align: top;">
                    <th class="width-medium pr-20 height-50">Postleitzahl des Veranstaltungsorts</th>
                    <td class="height-50"><input type="text" v-model="formData.eventPostalCode" class="width-half-full" />
                        <ErrorText :message="errors.eventPostalCode" /></td>
                </tr>

                <tr style="vertical-align: top;">
                    <th class="width-medium pr-20 height-50">E-Mail-Adresse der Veranstaltungsleitung</th>
                    <td class="height-50"><input type="email" v-model="formData.eventEmail" class="width-half-full" />
                        <ErrorText :message="errors.eventEmail" /></td>
                </tr>

                <tr style="vertical-align: top;">
                    <th class="width-medium pr-20 height-50">Beginn</th>
                    <td class="height-50"><input type="date" v-model="formData.eventBegin" class="width-half-full" />
                        <ErrorText :message="errors.eventBegin" /></td>
                </tr>

                <tr style="vertical-align: top;">
                    <th class="width-medium pr-20 height-50">Ende</th>
                    <td class="height-50"><input type="date" v-model="formData.eventEnd" class="width-half-full" />
                        <ErrorText :message="errors.eventEnd" /></td>
                </tr>

                <tr style="vertical-align: top;">
                    <th class="width-medium pr-20 height-50">Ende Early-Bird-Phase</th>
                    <td class="height-50"><input type="date" v-model="formData.eventEarlyBirdEnd" class="width-half-full" />
                        <ErrorText :message="errors.eventEarlyBirdEnd" /></td>
                </tr>

                <tr style="vertical-align: top;">
                    <th class="width-medium pr-20 height-50">Finaler Anmeldeschluss</th>
                    <td class="height-50"><input type="date" v-model="formData.eventRegistrationFinalEnd" class="width-half-full" />
                        <ErrorText :message="errors.eventRegistrationFinalEnd" />
                    </td>
                </tr>

                <tr style="vertical-align: top;">
                    <th class="width-medium pr-20 height-50">Beitragsart</th>
                    <td class="height-50">
                        <select v-model="formData.eventParticipationFeeType" class="width-half-full">
                            <option value="fixed">Festpreis</option>
                            <option value="solidarity">Solidaritätsprinzip</option>
                        </select>
                    </td>
                </tr>


                <tr style="vertical-align: top;">
                    <th class="width-medium pr-20 height-50">Preiserhöhung nach Early-Bird-Phase</th>
                    <td class="height-50"><input type="number" v-model="formData.eventEarlyBirdEndAmountIncrease" class="width-tiny" />%</td>
                </tr>

                <tr style="vertical-align: top;">
                    <th class="width-medium pr-20 height-50">Veranstsaltungs-Konto</th>
                    <td class="height-50"><input type="text" v-model="formData.eventAccount" class="width-full" />
                        <ErrorText :message="errors.eventAccount" /></td>
                </tr>

                <tr style="vertical-align: top;">
                    <th class="width-medium pr-20 height-50">Veranstaltungs-IBAN</th>
                    <td class="height-50"><input type="text" v-model="formData.eventIban" class="width-full" />
                        <ErrorText :message="errors.eventIban" /></td>
                </tr>

                <tr style="vertical-align: top;">
                    <td colspan="2" style="font-weight: bold;">
                        <input type="checkbox" v-model="formData.eventPayPerDay">
                        Beitrag abhängig von Anwesenheitstagen
                    </td>
                </tr>

                <tr>
                    <td colspan="2" class="pt-20">
                        <input type="button" value="Veranstaltung erstellen" @click="createEvent" />
                    </td>
                </tr>
            </table>


        </fieldset>
    </AppLayout>
</template>

<style scoped>

</style>
