document.addEventListener('turbo:load', loadLeftHeaderNavData)

function loadLeftHeaderNavData () {

}

listen('change', '.is-action-enable', function (event) {
    let leftHeaderId = $(event.currentTarget).attr('data-id')
    $.ajax({
        url: $('#leftHeaderNavigationUrl').val() + '/' + leftHeaderId +
            '/enable-disable',
        method: 'post',
        cache: false,
        success: function (result) {
            if (result.success) {
                displaySuccessMessage(result.message)
                window.livewire.emit('refresh')
            }
        },
    })
})

listen('change', '.left-header-change-status', function (event) {
    let leftHeaderId = $(event.currentTarget).attr('data-id')
    $.ajax({
        url: $('#leftHeaderNavigationUrl').val() + '/' + leftHeaderId +
            '/change-status',
        method: 'post',
        cache: false,
        success: function (result) {
            if (result.success) {
                displaySuccessMessage(result.message)
                window.livewire.emit('refresh')
            }
        },
    })
})

listenClick('.left-header-url-edit-btn', function (event) {
    if ($('.ajaxCallIsRunning').val()) {
        return
    }
    ajaxCallInProgress()
    let leftHeaderUrlId = $(event.currentTarget).attr('data-id')
    renderLeftHeaderURL(leftHeaderUrlId)
})

function renderLeftHeaderURL (id) {
    $.ajax({
        url: $('#leftHeaderNavigationUrl').val() + '/' + id + '/change-url',
        type: 'GET',
        success: function (result) {
            if (result.success) {
                let leftHeaderURL = result.data
                $('#addLeftHeaderURLId').val(leftHeaderURL.id)
                $('#leftHeaderURL').val(leftHeaderURL.url)
                $('#updateLeftHeaderURLModal').modal('show')
                ajaxCallCompleted()
            }
        },
        error: function (result) {
            manageAjaxErrors(result)
        },
    })
}

listenSubmit('#updateLeftHeaderURLForm', function (event) {
    event.preventDefault()
    var loadingButton = jQuery(this).find('#updateLeftHeaderURLBtn')
    loadingButton.button('loading')
    let id = $('#addLeftHeaderURLId').val()

    $.ajax({
        url: $('#leftHeaderNavigationUrl').val() + '/' + id + '/' +
            'update-url',
        type: 'post',
        data: $(this).serialize(),
        success: function (result) {
            if (result.success) {
                window.livewire.emit('refresh')
                displaySuccessMessage(result.message)
                $('#updateLeftHeaderURLModal').modal('hide')
                $(loadingButton).attr('disabled', false)
            }
        },
        error: function (result) {
            UnprocessableInputError(result)
        },
        complete: function () {
            loadingButton.button('reset')
        },
    })
})
