/**
 * Vermietung Admin JS — js/vermietung-admin.js
 *
 * Admin-JavaScript für den Vermietungsmodus.
 * Tab-Navigation, Media-Upload, Ausstattung, Suche.
 *
 * @package PocketBookingPro
 */

(function($) {
    'use strict';

    /* ===== Tab-Navigation ===== */
    $(document).on('click', '.simpbook-tabs .nav-tab', function(e) {
        e.preventDefault();
        var targetTab = $(this).data('tab');
        if (!targetTab) return;

        // Tabs umschalten
        $(this).siblings('.nav-tab').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');

        // Inhalte umschalten
        $(this).closest('form').find('.simpbook-tab-content').hide();
        $('#' + targetTab).show();

        // Hash setzen (für Neuladen)
        if (history.replaceState) {
            history.replaceState(null, null, '#' + targetTab);
        }
    });

    // Beim Laden: Hash prüfen
    $(function() {
        var hash = window.location.hash;
        if (hash && $(hash).length && $(hash).hasClass('simpbook-tab-content')) {
            var tabLink = $('[data-tab="' + hash.replace('#', '') + '"]');
            if (tabLink.length) {
                tabLink.trigger('click');
            }
        }
    });

    /* ===== Media-Upload: Titelbild ===== */
    $(document).on('click', '#simpbook-titelbild-waehlen', function(e) {
        e.preventDefault();
        var frame = wp.media({
            title: 'Titelbild wählen',
            multiple: false,
            library: { type: 'image' }
        });
        frame.on('select', function() {
            var attachment = frame.state().get('selection').first().toJSON();
            $('#simpbook_titelbild_id').val(attachment.id);
            var imgUrl = attachment.sizes && attachment.sizes.medium
                ? attachment.sizes.medium.url
                : attachment.url;
            $('#simpbook-titelbild-preview').html(
                '<img src="' + imgUrl + '" style="max-width: 300px; border-radius: 8px;">'
            );
            $('#simpbook-titelbild-entfernen').show();
        });
        frame.open();
    });

    $(document).on('click', '#simpbook-titelbild-entfernen', function(e) {
        e.preventDefault();
        $('#simpbook_titelbild_id').val('');
        $('#simpbook-titelbild-preview').empty();
        $(this).hide();
    });

    /* ===== Media-Upload: Galerie ===== */
    $(document).on('click', '#simpbook-galerie-hinzufuegen', function(e) {
        e.preventDefault();
        var frame = wp.media({
            title: 'Bilder hinzufügen',
            multiple: true,
            library: { type: 'image' }
        });
        frame.on('select', function() {
            var attachments = frame.state().get('selection').toJSON();
            var preview = $('#simpbook-galerie-preview');
            var idsInput = $('#simpbook_bilder_ids');
            var currentIds = idsInput.val() ? idsInput.val().split(',').map(Number) : [];

            attachments.forEach(function(att) {
                if (currentIds.indexOf(att.id) === -1) {
                    currentIds.push(att.id);
                    var thumbUrl = att.sizes && att.sizes.thumbnail
                        ? att.sizes.thumbnail.url
                        : att.url;
                    preview.append(
                        '<div class="simpbook-galerie-bild" data-id="' + att.id + '" style="position: relative;">' +
                            '<img src="' + thumbUrl + '" style="border-radius: 4px; width: 80px; height: 80px; object-fit: cover;">' +
                            '<button type="button" class="simpbook-galerie-remove" style="position: absolute; top: -5px; right: -5px; background: #b32d2e; color: #fff; border: none; border-radius: 50%; width: 20px; height: 20px; cursor: pointer; font-size: 12px; line-height: 18px;">&times;</button>' +
                        '</div>'
                    );
                }
            });
            idsInput.val(currentIds.join(','));
        });
        frame.open();
    });

    $(document).on('click', '.simpbook-galerie-remove', function(e) {
        e.preventDefault();
        var bild = $(this).closest('.simpbook-galerie-bild');
        var removeId = parseInt(bild.data('id'), 10);
        bild.remove();

        var idsInput = $('#simpbook_bilder_ids');
        var ids = idsInput.val().split(',').map(Number).filter(function(id) {
            return id !== removeId && id > 0;
        });
        idsInput.val(ids.join(','));
    });

    /* ===== Ausstattung hinzufügen/entfernen ===== */
    $(document).on('click', '#simpbook-add-ausstattung', function(e) {
        e.preventDefault();
        $('#simpbook-ausstattung-liste').append(
            '<div class="simpbook-ausstattung-item" style="display: flex; gap: 8px; margin-bottom: 5px;">' +
                '<input type="text" name="simpbook_ausstattung[]" value="" class="regular-text" placeholder="z.B. WLAN, Klimaanlage, Parkplatz...">' +
                '<button type="button" class="button simpbook-remove-ausstattung">&times;</button>' +
            '</div>'
        );
        // Fokus aufs neue Feld
        $('#simpbook-ausstattung-liste .simpbook-ausstattung-item:last input').focus();
    });

    $(document).on('click', '.simpbook-remove-ausstattung', function(e) {
        e.preventDefault();
        $(this).closest('.simpbook-ausstattung-item').remove();
    });

    /* ===== Profilfoto (Gastgeber) ===== */
    $(document).on('click', '#simpbook-profilfoto-waehlen', function(e) {
        e.preventDefault();
        var frame = wp.media({
            title: 'Profilfoto wählen',
            multiple: false,
            library: { type: 'image' }
        });
        frame.on('select', function() {
            var attachment = frame.state().get('selection').first().toJSON();
            var url = attachment.sizes && attachment.sizes.thumbnail
                ? attachment.sizes.thumbnail.url
                : attachment.url;
            $('#simpbook_profilfoto_url').val(attachment.url);
            $('#simpbook-profilfoto-preview').html(
                '<img src="' + url + '" style="max-width: 150px; border-radius: 50%;">'
            );
            $('#simpbook-profilfoto-entfernen').show();
        });
        frame.open();
    });

    $(document).on('click', '#simpbook-profilfoto-entfernen', function(e) {
        e.preventDefault();
        $('#simpbook_profilfoto_url').val('');
        $('#simpbook-profilfoto-preview').empty();
        $(this).hide();
    });

    /* ===== Unterkunft-Suche (Liste) ===== */
    $(document).on('input', '#unterkuenfte-search-input', function() {
        var search = $(this).val().toLowerCase();
        $('.simpbook-unterkuenfte-table tbody tr').each(function() {
            var data = $(this).data('search') || '';
            $(this).toggle(data.indexOf(search) !== -1);
        });
    });

    /* ===== Vermietungsart → Zimmer-Postbox Ein/Ausblenden ===== */
    $(document).on('change', '#simpbook_vermietungsart', function() {
        var zimmerBox = $('#simpbook-zimmer-postbox');
        if ($(this).val() === 'zimmer') {
            zimmerBox.slideDown(200);
        } else {
            zimmerBox.slideUp(200);
        }
    });

    /* ===== Zimmer CRUD ===== */

    // Hilfsfunktion: Sammelt Daten aus einem Zimmer-Formular-Container
    function getZimmerFormData(container) {
        return {
            zimmer_id:         container.find('.simpbook-zimmer-field-id').val(),
            unterkunft_id:     $('#simpbook-unterkunft-form').data('unterkunft-id'),
            name:              container.find('.simpbook-zimmer-field-name').val(),
            beschreibung:      container.find('.simpbook-zimmer-field-beschreibung').val(),
            zimmer_typ:        container.find('.simpbook-zimmer-field-typ').val(),
            preis_pro_nacht:   container.find('.simpbook-zimmer-field-preis').val(),
            preis_pro_woche:   container.find('.simpbook-zimmer-field-preis-woche').val(),
            rabatt_preis_nacht:container.find('.simpbook-zimmer-field-rabatt').val(),
            max_gaeste:        container.find('.simpbook-zimmer-field-gaeste').val(),
            schlafplaetze:     container.find('.simpbook-zimmer-field-schlafplaetze').val(),
            zimmergroesse:     container.find('.simpbook-zimmer-field-groesse').val(),
            anzahl_verfuegbar: container.find('.simpbook-zimmer-field-verfuegbar').val(),
            betten_beschreibung: container.find('.simpbook-zimmer-field-betten').val(),
            aktiv:             container.find('.simpbook-zimmer-field-aktiv').is(':checked') ? 1 : 0,
            simpbook_nonce:    simpbookVermietung.zimmer_nonce,
            action:            'simpbook_vermietung_zimmer_speichern'
        };
    }

    // Zimmer hinzufügen Button → Neues-Formular anzeigen
    $(document).on('click', '#simpbook-zimmer-hinzufuegen', function() {
        var form = $('#simpbook-neues-zimmer-form');
        form.slideDown(200);
        form.find('.simpbook-zimmer-field-name').focus();
        $(this).hide();
    });

    // Bearbeiten Button
    $(document).on('click', '.simpbook-zimmer-edit', function() {
        var row = $(this).closest('.simpbook-zimmer-row');
        var editForm = row.find('.simpbook-zimmer-edit-form');

        // Alle anderen Edit-Formulare schließen
        $('.simpbook-zimmer-edit-form').not(editForm).slideUp(200);

        editForm.slideToggle(200);
    });

    // Abbrechen Button
    $(document).on('click', '.simpbook-zimmer-cancel', function() {
        var formContainer = $(this).closest('.simpbook-zimmer-edit-form, #simpbook-neues-zimmer-form');
        formContainer.slideUp(200);

        // Bei neuem Zimmer: Button wieder zeigen
        if (formContainer.attr('id') === 'simpbook-neues-zimmer-form') {
            $('#simpbook-zimmer-hinzufuegen').show();
        }
    });

    // Zimmer speichern (Neu oder Bearbeiten)
    $(document).on('click', '.simpbook-zimmer-save', function() {
        var btn = $(this);
        var formContainer = btn.closest('.simpbook-zimmer-edit-form, #simpbook-neues-zimmer-form');
        var spinner = formContainer.find('.simpbook-zimmer-spinner');
        var data = getZimmerFormData(formContainer);

        // Validierung
        if (!data.name || !data.name.trim()) {
            alert(simpbookVermietung.i18n.zimmer_name_required);
            formContainer.find('.simpbook-zimmer-field-name').focus();
            return;
        }

        btn.prop('disabled', true);
        spinner.addClass('is-active');

        $.post(simpbookVermietung.ajax_url, data, function(response) {
            btn.prop('disabled', false);
            spinner.removeClass('is-active');

            if (response.success) {
                // Seite neu laden um die Zimmer-Liste zu aktualisieren
                window.location.reload();
            } else {
                alert(response.data || simpbookVermietung.i18n.error);
            }
        }).fail(function() {
            btn.prop('disabled', false);
            spinner.removeClass('is-active');
            alert(simpbookVermietung.i18n.error);
        });
    });

    // Zimmer löschen
    $(document).on('click', '.simpbook-zimmer-delete', function() {
        if (!confirm(simpbookVermietung.i18n.confirm_delete_zimmer)) {
            return;
        }

        var row = $(this).closest('.simpbook-zimmer-row');
        var zimmerId = row.data('zimmer-id');
        var unterkunftId = $('#simpbook-unterkunft-form').data('unterkunft-id');

        $.post(simpbookVermietung.ajax_url, {
            action:         'simpbook_vermietung_zimmer_loeschen',
            zimmer_id:      zimmerId,
            unterkunft_id:  unterkunftId,
            simpbook_nonce: simpbookVermietung.zimmer_delete_nonce
        }, function(response) {
            if (response.success) {
                row.slideUp(300, function() { row.remove(); });
            } else {
                alert(response.data || simpbookVermietung.i18n.error);
            }
        }).fail(function() {
            alert(simpbookVermietung.i18n.error);
        });
    });

})(jQuery);
