jQuery('#year-tabs').tabs();

jQuery(document).on('change', '#year-select', function () {
    var year = jQuery(this).val();
    jQuery(`.ui-tabs-tab a[href="#${year}"]`).trigger('click')
}).on('change', 'input[type="checkbox"][name="date"]', function () {
    var date = jQuery(this).data('date'),
        slot = jQuery(this).data('slot'),
        index = jQuery(this).data('index'),
        isChecked = jQuery(this).is(':checked');

    jQuery.ajax({
        method: 'POST',
        url: ajaxurl,
        data: {
            action: 'sbuy_booking_from_dashboard',
            date: date,
            slot: slot,
            index: index,
            isChecked: isChecked,
            nonce: sbuy_obj.nonce
        },
        success: function (response) {

        }
    })
});

jQuery(document).ready(function ($) {
    if ($('#booking-popup').length === 0) {
        $('body').append(`
            <div id="booking-popup">
                <h3>New Booking</h3>
                <label>Notes:<br><textarea id="booking-notes" style="width:100%" rows="5"></textarea></label>
                <label>Price:<br><input type="number" id="booking-price" style="width:100%"></label>
                <button id="generate-link" class="button button-primary">Generate Link</button>
                <small style="text-align: center">💡 Note: The message above will be visible to the customer and added to their calendar.</small>
                <button id="close-popup">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                      <path d="M6 6 L18 18 M18 6 L6 18" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                </button>
                <div id="generated-url" style="margin-top:10px; word-break:break-all;"></div>
            </div>
        `);
    }

    $(document).on('click', '#booking-open-popup', function () {
        $('#booking-popup')
            .css("display", "flex")
            .fadeIn();
    });

    $(document).on('click', '#close-popup', function () {
        $('#booking-popup').fadeOut();
    });

    $(document).on('click', '#copy-booking-link', async function () {
        const link = $('#generated-url a').text();
        await navigator.clipboard.writeText(link);
        $(this).text("Link copied!");
    });

    $(document).on('click', '#generate-link', function () {
        let notes = $('#booking-notes').val(),
            price = $('#booking-price').val();

        jQuery.ajax({
            method: 'POST',
            url: ajaxurl,
            data: {
                action: 'sbuy_booking_get_token',
                notes: notes,
                price: price,
                nonce: sbuy_obj.nonce
            },
            success: function (response) {
                if (response.data.url) {
                    $('#generated-url').html(`<a href="${response.data.url}" target="_blank">${response.data.url}</a><br><br><button id="copy-booking-link" class="button button-primary">Copy Link</button>`);
                }
            }
        })
    });

    // Bulk: block every occurrence of the selected weekday
    $(document).on('click', '#sbuy-bulk-block-btn', function () {
        var $select = $('#sbuy-bulk-day-select');
        var raw = $select.val();
        if (raw === '' || raw === null) return;
        var day = parseInt(raw, 10);
        var label = $select.find('option:selected').text().trim();
        if (!confirm(label + '?')) return;

        var $btn = $(this).prop('disabled', true);
        $.ajax({
            method: 'POST',
            url: ajaxurl,
            data: {
                action: 'sbuy_bulk_block_day',
                day: day,
                year: $('#year-select').val() || new Date().getFullYear(),
                nonce: sbuy_obj.nonce
            }
        }).done(function (response) {
            if (response && response.data && response.data.message) alert(response.data.message);
            window.location.reload();
        }).fail(function () {
            alert('Request failed.');
            $btn.prop('disabled', false);
        });
    });

    // Bulk: unblock everything that was bulk-blocked previously
    $(document).on('click', '#sbuy-bulk-unblock-all', function () {
        if (!confirm($(this).text().trim() + '?')) return;

        var $btn = $(this).prop('disabled', true);
        $.ajax({
            method: 'POST',
            url: ajaxurl,
            data: {
                action: 'sbuy_bulk_unblock_all',
                nonce: sbuy_obj.nonce
            }
        }).done(function (response) {
            if (response && response.data && response.data.message) alert(response.data.message);
            window.location.reload();
        }).fail(function () {
            alert('Request failed.');
            $btn.prop('disabled', false);
        });
    });
});