let calendar;
let travelEventSource;
const rootStyles = getComputedStyle(document.documentElement);
const background = rootStyles.getPropertyValue('--swal-bg')?.trim();
const color = rootStyles.getPropertyValue('--swal-text-color')?.trim();
document.addEventListener('DOMContentLoaded', async function () {
    await loadCompanies();

    const companyMap = getCompanyMap();

    const calendarEl = document.getElementById('calendar');

    // Build calendar
    calendar = new FullCalendar.Calendar(calendarEl, {
        initialDate: new Date().toISOString().split('T')[0],
        contentHeight: 'auto',
        initialView: 'dayGridMonth',
        aspectRatio: 3,
        fixedWeekCount: false,

        selectable: true,
        businessHours: true,
        dayMaxEvents: true,
        showNonCurrentDates: false,

        headerToolbar: {
            start: 'title',
            end: 'today prev,next',
        },


        datesSet: function (info) {
            const date = calendar.getDate();

            document.getElementById('calender_month').value =
                `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
        },

        eventContent: function (arg) {
            return {html: arg.event.title};
        },

        dateClick: function (info) {

            const clicked = info.date;
            const current = info.view.currentStart;

            // Compare month + year only
            const sameMonth =
                clicked.getMonth() === current.getMonth() &&
                clicked.getFullYear() === current.getFullYear();

            if (!sameMonth) {
                return; // ignore outside-month days
            }

            createTravelReimburse(info.dateStr);
        },

        // Open modal on click
        eventClick: function (info) {

            const event = info.event;

            document.getElementById('reimburse_uuid').value = event.id;
            document.getElementById('departure_postcode').value = event.extendedProps.departure;
            document.getElementById('destination_postcode').value = event.extendedProps.destination;
            document.getElementById('travel_distance').value = event.extendedProps.distance;
            document.getElementById('travel_date').value = event.extendedProps.travel_date;
            document.getElementById('homework').checked = event.extendedProps.homework;
            document.getElementById('office_travelreimburse_company_uuid').value = event.extendedProps.company;
            document.getElementById('travel_description').value = event.extendedProps.description ?? '';

            new bootstrap.Modal(document.getElementById('travelModal')).show();
        }
    });

    calendar.render();


    // Event retrievement
    travelEventSource = calendar.addEventSource({
        events: function (fetchInfo, successCallback, failureCallback) {

            const start = toYMD(fetchInfo.start);

            const endDate = new Date(fetchInfo.end);
            endDate.setDate(endDate.getDate() - 1);

            const end = toYMD(endDate);

            fetch(`/api/v1/office/travel-reimburse/?` +
                `builder[1][between][0]=travel_date&` +
                `builder[1][between][1]=${start}&` +
                `builder[1][between][2]=${end}`, {
                credentials: 'include'
            })
                .then(res => res.json())
                .then(data => {
                    let totalDistanceHomework = 0;
                    let totalDistanceBusiness = 0;

                    data.forEach(item => {
                        const distance = parseFloat(item.travel_distance) || 0;

                        if (Number(item.homework) === 1) {
                            totalDistanceHomework += distance;
                        } else {
                            totalDistanceBusiness += distance;
                        }
                    });

                    const total_homeWorkIncl = document.getElementById('total_travel_distance_homework_incl');
                    const total_homeWorkExcl = document.getElementById('total_travel_distance_homework_excl');
                    const total_businesskIncl = document.getElementById('total_travel_distance_business_incl');
                    const total_businessExcl = document.getElementById('total_travel_distance_business_excl');

                    if (total_homeWorkExcl) {
                        total_homeWorkExcl.textContent = `${totalDistanceHomework} km`;
                        total_homeWorkIncl.textContent = `${totalDistanceHomework} km`;
                    }

                    if (total_businesskIncl) {
                        total_businesskIncl.textContent = `${totalDistanceBusiness} km`;
                        total_businessExcl.textContent = `${totalDistanceBusiness} km`;
                    }

                    const formatEuro = amount =>
                        amount.toLocaleString('nl-NL', {
                            style: 'currency',
                            currency: 'EUR'
                        });

                    const parseEuro = (el) => {
                        if (!el) return 0;

                        // "€ 0,23" -> 0.23
                        return parseFloat(
                            el.textContent
                                .replace('€', '')
                                .replace(/\s/g, '')
                                .replace('.', '')
                                .replace(',', '.')
                        ) || 0;
                    };

                    const homeworkInclRate = parseEuro(document.getElementById('office_travelreimburse_cents_homework_incl'));
                    const homeworkExclRate = parseEuro(document.getElementById('office_travelreimburse_cents_homework_excl'));
                    const businessInclRate = parseEuro(document.getElementById('office_travelreimburse_cents_business_incl'));
                    const businessExclRate = parseEuro(document.getElementById('office_travelreimburse_cents_business_excl'));


                    document.getElementById('office_travelreimburse_cents_homework_incl_total').textContent =
                        formatEuro(totalDistanceHomework * homeworkInclRate);

                    document.getElementById('office_travelreimburse_cents_homework_excl_total').textContent =
                        formatEuro(totalDistanceHomework * homeworkExclRate);

                    document.getElementById('office_travelreimburse_cents_business_incl_total').textContent =
                        formatEuro(totalDistanceBusiness * businessInclRate);

                    document.getElementById('office_travelreimburse_cents_business_excl_total').textContent =
                        formatEuro(totalDistanceBusiness * businessExclRate);

                    document.getElementById('total_travel_incl').textContent =
                        formatEuro((totalDistanceBusiness * businessInclRate) + (totalDistanceHomework * homeworkInclRate));

                    document.getElementById('total_travel_excl').textContent =
                        formatEuro((totalDistanceBusiness * businessExclRate) + (totalDistanceHomework * homeworkExclRate));

                    const events = data.map(item => ({
                        id: item.reimburse_uuid,
                        title: `${item.travel_distance}km | ${companyMap[item.office_travelreimburse_company_uuid] ?? item.office_travelreimburse_company_uuid}`,
                        start: item.travel_date,

                        ...(item.homework === 1 && {
                            color: 'var(--bs-success)'
                        }),

                        extendedProps: {
                            departure: item.departure_postcode,
                            destination: item.destination_postcode,
                            distance: item.travel_distance,
                            travel_date: item.travel_date,
                            description: item.travel_description,
                            company: item.office_travelreimburse_company_uuid,
                            homework: item.homework
                        }
                    }));

                    successCallback(events);
                })
                .catch(failureCallback);
        }
    });
});

function toYMD(dateStr) {
    const d = new Date(dateStr);

    return d.getFullYear() + '-' +
        String(d.getMonth() + 1).padStart(2, '0') + '-' +
        String(d.getDate()).padStart(2, '0');
}

// Update from modal form
document.getElementById('saveTravelBtn').addEventListener('click', function () {

    const payload = {
        reimburse_uuid: document.getElementById('reimburse_uuid').value,
        departure_postcode: document.getElementById('departure_postcode').value,
        destination_postcode: document.getElementById('destination_postcode').value,
        travel_distance: document.getElementById('travel_distance').value,
        travel_description: document.getElementById('travel_description').value,
        travel_date: document.getElementById('travel_date').value,
        homework: document.getElementById('homework').checked,
        office_travelreimburse_company_uuid: document.getElementById('office_travelreimburse_company_uuid').value,
        "X-HTTP-Method-Override": "PUT"
    };

    $.post('/api/v1/office/travel-reimburse/', payload)
        .done(function (response) {

            if (response.error) {
                alert(response.error);
                return;
            }

            calendar.refetchEvents();

            // close modal
            bootstrap.Modal.getInstance(
                document.getElementById('travelModal')
            ).hide();
        })
        .fail(function (xhr) {
            console.error(xhr.responseText);
            alert('Something went wrong');
        });
});

document.getElementById('deleteTravelBtn').addEventListener('click', function () {

    const payload = {
        reimburse_uuid: document.getElementById('reimburse_uuid').value,
        "X-HTTP-Method-Override": "DELETE"
    };

    $.post('/api/v1/office/travel-reimburse/', payload)
        .done(function (response) {

            if (response.error) {
                alert(response.error);
                return;
            }

            calendar.refetchEvents();

            // close modal
            bootstrap.Modal.getInstance(
                document.getElementById('travelModal')
            ).hide();
        })
        .fail(function (xhr) {
            console.error(xhr.responseText);
            alert('Something went wrong');
        });
});

function createTravelReimburse(date) {

    const payload = {
        departure_postcode: document.getElementById('new_departure_postcode').value,
        destination_postcode: document.getElementById('new_destination_postcode').value,
        travel_distance: document.getElementById('new_travel_distance').value,
        homework: Number(document.getElementById('new_homework').checked),
        office_travelreimburse_company_uuid: document.getElementById('new_office_travelreimburse_company_uuid').value,
        travel_date: date,
        "X-HTTP-Method-Override": "POST"
    };

    $.post('/api/v1/office/travel-reimburse/', payload)
        .done(function (response) {

            if (response.error) {
                alert(response.error);
                return;
            }

            // refresh calendar
            calendar.refetchEvents();
        })
        .fail(function (xhr) {
            console.error(xhr.responseText);
            alert('Something went wrong');
        });
}

document.addEventListener('DOMContentLoaded', function () {

    const form = document.getElementById('defaultForNew');

    const fields = [
        'new_departure_postcode',
        'new_destination_postcode',
        'new_travel_distance',
        'new_homework',
        'new_office_travelreimburse_company_uuid'
    ];

    // Load defaults
    const defaults = JSON.parse(localStorage.getItem('travelDefaults') || '{}');

    fields.forEach(id => {
        const element = document.getElementById(id);

        if (!element || defaults[id] === undefined) return;

        if (element.type === 'checkbox') {
            element.checked = !!defaults[id];
        } else {
            element.value = defaults[id];
        }
    });

    // Save defaults
    form.addEventListener('submit', function (e) {
        e.preventDefault();

        const defaults = {};

        fields.forEach(id => {
            const el = document.getElementById(id);

            if (!el) return;

            if (el.type === 'checkbox') {
                defaults[id] = el.checked ? 1 : 0;
            } else {
                defaults[id] = el.value;
            }
        });

        localStorage.setItem('travelDefaults', JSON.stringify(defaults));

        Swal.fire({
            background: background,
            color: color,
            icon: 'success',
            title: __('default_saved'),
            text: __('default_have_been_saved'),
            timer: 700,
            showConfirmButton: false
        });
    });

});
