/**
 * Vermietung Frontend JS — js/vermietung-frontend.js
 *
 * Verfügbarkeitskalender, Preisberechnung, Buchungsformular.
 *
 * @package PocketBookingPro
 */

(function() {
    'use strict';

    var config = window.simpbookVermietungFrontend || {};
    var ajaxUrl = config.ajax_url || '';
    var nonce = config.nonce || '';
    var i18n = config.i18n || {};

    /* ===== Verfügbarkeitskalender ===== */
    var SimpbookKalender = {
        container: null,
        unterkunftId: null,
        zimmerId: null,
        currentYear: null,
        currentMonth: null,
        checkin: null,
        checkout: null,
        dayData: {},
        onSelect: null,

        init: function(el, opts) {
            this.container = el;
            this.unterkunftId = opts.unterkunftId || 0;
            this.zimmerId = opts.zimmerId || null;
            this.onSelect = opts.onSelect || null;

            var now = new Date();
            this.currentYear = now.getFullYear();
            this.currentMonth = now.getMonth() + 1;
            this.checkin = null;
            this.checkout = null;

            this.render();
            this.loadData();
        },

        render: function() {
            var self = this;
            var header = document.createElement('div');
            header.className = 'simpbook-kalender-header';

            var btnPrev = document.createElement('button');
            btnPrev.type = 'button';
            btnPrev.className = 'simpbook-kalender-nav';
            btnPrev.textContent = '‹';
            btnPrev.addEventListener('click', function() {
                self.prevMonth();
            });

            var btnNext = document.createElement('button');
            btnNext.type = 'button';
            btnNext.className = 'simpbook-kalender-nav';
            btnNext.textContent = '›';
            btnNext.addEventListener('click', function() {
                self.nextMonth();
            });

            var title = document.createElement('span');
            title.className = 'simpbook-kalender-title';
            var monatNamen = [
                'Januar','Februar','März','April','Mai','Juni',
                'Juli','August','September','Oktober','November','Dezember'
            ];
            title.textContent = monatNamen[this.currentMonth - 1] + ' ' + this.currentYear;

            header.appendChild(btnPrev);
            header.appendChild(title);
            header.appendChild(btnNext);

            // Grid
            var grid = document.createElement('div');
            grid.className = 'simpbook-kalender-grid';

            // Wochentag-Header (Mo-So)
            var tage = ['Mo','Di','Mi','Do','Fr','Sa','So'];
            tage.forEach(function(t) {
                var dh = document.createElement('div');
                dh.className = 'simpbook-kalender-day-header';
                dh.textContent = t;
                grid.appendChild(dh);
            });

            // Tage berechnen
            var firstDay = new Date(this.currentYear, this.currentMonth - 1, 1);
            var lastDay = new Date(this.currentYear, this.currentMonth, 0);
            var startWeekday = firstDay.getDay(); // 0=So
            startWeekday = startWeekday === 0 ? 7 : startWeekday; // 1=Mo

            // Leere Zellen
            for (var e = 1; e < startWeekday; e++) {
                var empty = document.createElement('div');
                empty.className = 'simpbook-kalender-day empty';
                grid.appendChild(empty);
            }

            // Tage
            for (var d = 1; d <= lastDay.getDate(); d++) {
                var dayEl = document.createElement('div');
                dayEl.className = 'simpbook-kalender-day';
                dayEl.textContent = d;
                dayEl.dataset.date = this.formatDate(this.currentYear, this.currentMonth, d);

                var dateStr = dayEl.dataset.date;
                var status = this.dayData[dateStr] || 'loading';
                dayEl.classList.add(status);

                // Selected / in-range markieren
                if (this.checkin && dateStr === this.checkin) {
                    dayEl.classList.add('selected');
                }
                if (this.checkout && dateStr === this.checkout) {
                    dayEl.classList.add('selected');
                }
                if (this.checkin && this.checkout && dateStr > this.checkin && dateStr < this.checkout) {
                    dayEl.classList.add('in-range');
                }

                // Click-Handler
                (function(dateStr, el) {
                    el.addEventListener('click', function() {
                        self.onDayClick(dateStr);
                    });
                })(dateStr, dayEl);

                grid.appendChild(dayEl);
            }

            // Container updaten
            this.container.innerHTML = '';
            this.container.appendChild(header);
            this.container.appendChild(grid);
        },

        loadData: function() {
            var self = this;
            var formData = new FormData();
            formData.append('action', 'simpbook_verfuegbarkeit_kalender');
            formData.append('nonce', nonce);
            formData.append('unterkunft_id', this.unterkunftId);
            formData.append('jahr', this.currentYear);
            formData.append('monat', this.currentMonth);
            if (this.zimmerId) {
                formData.append('zimmer_id', this.zimmerId);
            }

            fetch(ajaxUrl, { method: 'POST', body: formData })
                .then(function(r) { return r.json(); })
                .then(function(resp) {
                    if (resp.success && resp.data && resp.data.tage) {
                        self.dayData = resp.data.tage;
                        self.render();
                    }
                })
                .catch(function() {
                    // Stille Fehlerbehandlung
                });
        },

        prevMonth: function() {
            this.currentMonth--;
            if (this.currentMonth < 1) {
                this.currentMonth = 12;
                this.currentYear--;
            }
            this.render();
            this.loadData();
        },

        nextMonth: function() {
            this.currentMonth++;
            if (this.currentMonth > 12) {
                this.currentMonth = 1;
                this.currentYear++;
            }
            this.render();
            this.loadData();
        },

        onDayClick: function(dateStr) {
            var status = this.dayData[dateStr];
            if (status !== 'verfuegbar') return;

            if (!this.checkin || (this.checkin && this.checkout)) {
                // Neuen Checkin setzen
                this.checkin = dateStr;
                this.checkout = null;
            } else {
                // Checkout setzen
                if (dateStr > this.checkin) {
                    this.checkout = dateStr;
                } else {
                    // Neuer Checkin (war vor altem)
                    this.checkin = dateStr;
                    this.checkout = null;
                }
            }

            this.render();

            if (this.onSelect) {
                this.onSelect(this.checkin, this.checkout);
            }
        },

        formatDate: function(y, m, d) {
            return y + '-' + String(m).padStart(2, '0') + '-' + String(d).padStart(2, '0');
        }
    };

    /* ===== Preisberechnung ===== */
    function berechnePreis(unterkunftId, zimmerId, checkin, checkout, codeEl, resultEl) {
        if (!checkin || !checkout) return;

        var formData = new FormData();
        formData.append('action', 'simpbook_vermietung_preis_berechnen');
        formData.append('nonce', nonce);
        formData.append('unterkunft_id', unterkunftId);
        formData.append('checkin', checkin);
        formData.append('checkout', checkout);
        if (zimmerId) formData.append('zimmer_id', zimmerId);
        if (codeEl && codeEl.value) formData.append('rabatt_code', codeEl.value);

        fetch(ajaxUrl, { method: 'POST', body: formData })
            .then(function(r) { return r.json(); })
            .then(function(resp) {
                if (resp.success && resp.data) {
                    var d = resp.data;
                    var html = '<div class="simpbook-preis-aufstellung">';
                    html += '<div class="simpbook-preis-zeile"><span>' + d.naechte + ' Nächte × ' + formatPreis(d.preis_pro_nacht) + '</span><span>' + formatPreis(d.naechte_gesamt) + '</span></div>';
                    if (d.reinigungsgebuehr > 0) {
                        html += '<div class="simpbook-preis-zeile"><span>Reinigungsgebühr</span><span>' + formatPreis(d.reinigungsgebuehr) + '</span></div>';
                    }
                    if (d.rabatt > 0) {
                        html += '<div class="simpbook-preis-zeile" style="color:#00a32a;"><span>Rabatt</span><span>-' + formatPreis(d.rabatt) + '</span></div>';
                    }
                    html += '<div class="simpbook-preis-zeile simpbook-preis-total"><span>Gesamt</span><span>' + formatPreis(d.gesamt) + '</span></div>';
                    html += '</div>';
                    resultEl.innerHTML = html;
                }
            })
            .catch(function() {
                resultEl.innerHTML = '';
            });
    }

    function formatPreis(betrag) {
        return parseFloat(betrag).toFixed(2).replace('.', ',') + ' €';
    }

    /* ===== Buchungsformular ===== */
    function initBuchungsFormular(form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();

            var btn = form.querySelector('.simpbook-btn-buchen');
            if (btn) {
                btn.disabled = true;
                btn.textContent = '...';
            }

            var formData = new FormData(form);
            formData.append('action', 'simpbook_vermietung_buchen');
            formData.append('nonce', nonce);

            fetch(ajaxUrl, { method: 'POST', body: formData })
                .then(function(r) { return r.json(); })
                .then(function(resp) {
                    if (resp.success) {
                        // Erfolg: Meldung anzeigen
                        var msg = document.createElement('div');
                        msg.style.cssText = 'background: #d4edda; color: #155724; padding: 16px; border-radius: 8px; margin-top: 12px; text-align: center;';
                        msg.innerHTML = '<strong>✓ ' + (resp.data.message || 'Buchung erfolgreich!') + '</strong>';
                        form.parentNode.insertBefore(msg, form.nextSibling);
                        form.style.display = 'none';
                    } else {
                        alert(resp.data && resp.data.message ? resp.data.message : i18n.buchung_fehler);
                    }
                })
                .catch(function() {
                    alert(i18n.buchung_fehler || 'Fehler bei der Buchung.');
                })
                .finally(function() {
                    if (btn) {
                        btn.disabled = false;
                        btn.textContent = 'Jetzt buchen';
                    }
                });
        });
    }

    /* ===== Initialisierung ===== */
    document.addEventListener('DOMContentLoaded', function() {
        // Kalender initialisieren
        var kalenderEls = document.querySelectorAll('.simpbook-verfuegbarkeit-kalender');
        kalenderEls.forEach(function(el) {
            var unterkunftId = el.dataset.unterkunftId || 0;
            var zimmerId = el.dataset.zimmerId || null;
            var checkinInput = document.querySelector(el.dataset.checkinInput || '#simpbook_checkin');
            var checkoutInput = document.querySelector(el.dataset.checkoutInput || '#simpbook_checkout');
            var preisEl = el.closest('.simpbook-buchung-sidebar')
                ? el.closest('.simpbook-buchung-sidebar').querySelector('.simpbook-preis-ergebnis')
                : null;

            var kal = Object.create(SimpbookKalender);
            kal.init(el, {
                unterkunftId: unterkunftId,
                zimmerId: zimmerId,
                onSelect: function(checkin, checkout) {
                    if (checkinInput) checkinInput.value = checkin || '';
                    if (checkoutInput) checkoutInput.value = checkout || '';
                    if (checkin && checkout && preisEl) {
                        var codeInput = document.querySelector('#simpbook_rabatt_code');
                        berechnePreis(unterkunftId, zimmerId, checkin, checkout, codeInput, preisEl);
                    }
                }
            });
        });

        // Buchungsformulare
        var formulare = document.querySelectorAll('.simpbook-buchung-form');
        formulare.forEach(function(form) {
            initBuchungsFormular(form);
        });
    });

})();
