$('.update_profile_button').click(async function (e) {
    e.preventDefault();

    let form = $('.update_profile_form');
    let data = new FormData(form[0]),
        url = form.attr('action'),
        method = form.attr('method');

    const response=await ajax({
        url,
        data,
        dataType: 'json',
        method,
        contentType: false,
        processData: false,
    });

    if (response.errors) {
        toasterError(response.errors);
    }
    if (response.message) {
        toasterSuccess(response.message);
        $('.info-modal').modal('hide');
        setTimeout(function () {
            window.location.reload();
        }, 200)
    }
});

$('.add_edit_hall_button').click(async function (e) {
    e.preventDefault();

    let form = $(this).parents('form.add_edit_hall_form'),
        data = new FormData(form[0]),
        url = form.attr('action'),
        method = form.attr('method');

    $('.discount_dates_input').each(function () {
        if ($(this).prop('checked') === false){
            data.append('discount_dates[]', 0);
            data.append('discount_percentage[]', 'empty');
        } else {
            data.append('discount_dates[]', 1);
            let inputSibling = $(this).siblings('.discount_percentage');
            data.append('discount_percentage[]', inputSibling.val());

        }
    });

    const response=await ajax({
        url,
        data,
        dataType: 'json',
        method
    });

    if (response.url){
        window.location.href = response.url;
    }

    if (response.errors){
        toasterError(response.errors);
    }


});

$(document).on('change', '.added_services_image',function (e) {
    $(this).siblings('input[name="old_added_services_image[]"]').val('new_image_added')
});

// Available days block
$('.add_available_dates_link').click(function (e) {
    e.preventDefault();
    let target = $(this).data('target');
    let counter = $($(this).data('target')).children('.deleted_available_dates_container').length+2;
    $($(this).data('target')).append(`<div class="deleted_available_dates_container row flex-row-reverse justify-content-between align-items-center align-content-center">
                            <div class="form-group col-md-5">
                                <div class="custom-control custom-checkbox">
                                    <div class="discount_dates_container d-flex justify-content-start align-content-center align-items-center">
                                        <input type="checkbox" value="1" class="custom-control-input discount_dates_input" id="discount_dates_`+target+counter+`">
                                        <label class="custom-control-label col-md-4" for="discount_dates_`+target+counter+`"> `+discount_dates+`</label>
                                    </div>
                                </div>
                            </div>
                             <div class="form-group col-md-3">
                                <input type="text" placeholder="`+available_dates_to+`" name="available_dates_to[]" value="" class="available_dates datepicker available_dates_to form-control">
                            </div>
                            <div class="form-group col-md-3">
                                <input type="text" placeholder="`+available_dates_from+`" name="available_dates_from[]" value="" class="available_dates datepicker available_dates_from form-control">
                            </div>
                            <div class="form-group col-md-1">
                                <a class="btn btn-danger delete_available_dates_link" href="#"><i class="fa fa-times"></i></a>
                            </div>
                        </div>`);

    counter = counter+1;
});
$(document).on('click', '.discount_dates_input', function () {
    if ($(this).prop('checked') === true){
        $(this).siblings('input[name="discount_percentage[]"]').remove();
        $(this).parents('.discount_dates_container').append(`<input type="number" min="1" pattern="/[1-9]/" class="discount_percentage col-md-8 form-control" placeholder="`+discount_percentage+`" value="">`)
    } else {
        $(this).siblings('.discount_percentage').remove();
    }
});


$('body').on('DOMNodeInserted', '.available_dates_container_person, .available_dates_container_days', function(e) {
    if ($(e.target).find('.available_dates')) {
        $('.available_dates').datepicker()
    }
});

let deleteHallRoute = null,
    deletedHall = null;

$(document).on('click', '.delete_hall_link', function (e) {
    e.preventDefault();
    deleteHallRoute = $(this).data('href');
    deletedHall = $(this).parents('.deleted_hall');
});

$('.delete_hall_modal_button').click(async function (e) {
    e.preventDefault();

    $(this).prop('disabled', true);
    let url = deleteHallRoute,
        method = 'get';
    const response=await ajax({
        url,
        dataType: 'json',
        method,
        contentType: false,
        processData: false,
    });

    if (response.errors) {
        $(this).removeAttr('disabled');
        toasterError(response.errors);
    }
    if (response.message) {
        toasterSuccess(response.message);
        $('.modal').modal('hide');
        $(this).removeAttr('disabled');
        deletedHall.remove();
    }

});

$('.reservation_status').click(function () {
    $('.search_result_container, .search_reservation_result_container').addClass('d-none');
    $('.search_result_container_body, .search_reservation_result_container_body').html('');
});

$('.search_form').submit(function(e){
    e.preventDefault();
});

$('input[name="re_date_from"], input[name="re_date_to"], select[name="is_paid"]').change(async function (e) {
    e.preventDefault();
    let data = {
            re_date_from: $('input[name="re_date_from"]').val(),
            re_date_to: $('input[name="re_date_to"]').val(),
            is_paid: $('select[name="is_paid"]').val(),
        },
        url = providerWalletSearchRoute,
        method = 'get';

    const response=await ajax({
        url,
        data,
        dataType: 'html',
        method
    });

    if(response){
        $('table.wallet_table tbody').html(response);
    }
});

$('.search_reservation_button').click(async function (e) {
    e.preventDefault();

    let form = $('.search_reservation_form');
    let data = new FormData(form[0]),
        url = form.attr('action'),
        method = form.attr('method');

    const response=await ajax({
        url,
        data,
        dataType: 'html',
        method
    });

    if(response){
        $('.search_reservation_result_container').removeClass('d-none');
        $('.search_reservation_result_container_body').html(response);
    }
});


$('select[name="region_id"], select[name="city_id"]').change(async function (e) {

    let target = $(this).data('target'),
        region = $('select[name="region_id"]'+target),
        city = $('select[name="city_id"]'+target),
        sector = $('select[name="sector_id"]'+target);

        let data = {
            region_id: region.val(),
            city_id: city.val()
        },
        url = getCityAndSectorRoute,
        method = 'get';

    if (region.val() === '' ){
        city.html(`<option value=""> `+region_name+` </option>`);
        sector.html(`<option value=""> `+region_name+` </option>`);
        return false;
    }

    if (e.target.name === 'region_id'){
        city.html(`<option value=""> '+city_name+' </option>`);
        sector.html(`<option value=""> `+city_name+` </option>`);
        data.city_id = null;
    }

    if (city.val() === '' || e.target.name === 'city_id'){
        sector.html(`<option value=""> `+sector_name+` </option>`);
    }


    const response=await ajax({
        url,
        data,
        dataType: 'json',
        method
    });

    if (response.cities.length && !response.sectors.length){
        city.html(`<option value=""> `+city_name+` </option>`);
        for(let i = 0; i < response.cities.length; i++){
            city.append(`<option value="`+response.cities[i].id+`">`+response.cities[i].name+`</option>`)
        }
    }
    if (response.sectors.length){
        sector.html(`<option value=""> `+sector_name+` </option>`);
        for(let i = 0; i < response.sectors.length; i++){
            sector.append(`<option value="`+response.sectors[i].id+`">`+response.sectors[i].name+`</option>`)
        }
    }

});

$(document).on('click', '.add_service',function (e) {
    e.preventDefault();
    let counter = $(this).parents('.service_container').children('.deleted_service').length+1;
    let serviceDiv = `
                 <div class="deleted_service">
                    <div class="in-flex justify-content-between">
                        <a href="#" class="delete_service"><i class="fa fa-trash text-danger"></i></a>
                        <h5 class="loc_title mb-4">`+added_services+`</h5>
                        <button class="addAnother btn add_service" type="button"><img src="`+addServiceIcon+`" alt=""></button>
                    </div>
                    <div class="row mt-1">
                        <div class="col-md-6">
                            <div class="form-group">
                                 <input name="added_services_name[]" type="text" class="form-control" autocomplete="off" autofocus />
                                <label class="floating-label">`+added_services_name+`</label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <input name="added_services_price[]" type="number" min="1" class="form-control" autocomplete="off" autofocus  />
                                <label class="floating-label"> `+added_services_price+`</label>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="form-group">
                                <textarea name="added_services_description[]" class="form-control" rows="2" autocomplete="off" autofocus ></textarea>
                                <label class="floating-label">`+added_services_description+`</label>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="form-group file-input-group">
                                <div class="wrap">
                                    <div class="file">
                                        <div class="added_service_input file__input" id="file__input">
                                            <input type="hidden" name="old_added_services_image[]" value="">
                                            <input class="file__input--file added_services_image" id="customAddedServiceImageFile_`+counter+`" type="file"  name="added_services_image[]" />
                                            <label class="file__input--label" for="customAddedServiceImageFile_`+counter+`" data-text-btn="`+select+`">    `+added_services_image+`  :</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>`;

    $(this).parents('.service_container').append(serviceDiv);

});

$(document).on('click', '.delete_service', function (e) {
    e.preventDefault();
    $(this).parents('.deleted_service').remove();
});

$(document).on('click', '.delete_available_dates_link', function(e){
    e.preventDefault();
    $(this).parents('.deleted_available_dates_container').remove();
    counter = counter+1;
});

$(document).on('click', '.mark_as_read_link',async function (e) {
    e.preventDefault();

    let url = markAsReadRoute,
        method = 'get';

    const response=await ajax({
        url,
        dataType: 'json',
        method,
        contentType: false,
        processData: false,
    });

    if (response.success) {
        $('.notification_count').html("(0)");
        $('.notifications_count_alert').remove();
        $('.notification_item').removeClass('bg-gray');
        $('.new').remove();
    }
});

$(document).on('click', '.refresh_notification', async function (e) {
    e.preventDefault();
    let method = 'get',
        url = refreshNotificationRoute;
    const response=await ajax({
        url,
        dataType: 'html',
        method,
        contentType: false,
        processData: false,
    });

    if (response) {
        $('.notification_container').html(response);
    }
});

$('.messages_link').click(function () {
    $('.messages_count_alert').remove();
});

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#imagePreview').css('background-image', 'url('+e.target.result +')');
            $('#imagePreview').hide();
            $('#imagePreview').fadeIn(650);
        }
        reader.readAsDataURL(input.files[0]);
    }
}

$("#imageUpload").change(function() {
    readURL(this);
});

$('.input-images').imageUploader({
    label: upload_hall_image,
});

$('#togglePassword').click(function() {
    const password = $('#password'),
        type = password.attr('type') === 'password' ? 'text' : 'password';
    password.attr('type', type);
    $(this).toggleClass('fa-eye-slash');
});


$(document).ready(function() {

    // ------------  File upload BEGIN ------------
    $('input[name="logo"]').on('change', function(event) {
        $('.logo_file_value').remove();
        var files = event.target.files;
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            $("<div class='logo_file_value file__value'><div class='file__value--text'>" + file.name + "</div><div class='file__value--remove' data-id='" + file.name + "' ></div></div>").insertAfter($(this).parents('.logo_file_input'));
        }
    });

    $(document).on('change', 'input[name="added_services_image[]"]', function(event) {
        $('.added_service_images').remove();
        var files = event.target.files;
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            $("<div class='added_service_images file__value'><div class='file__value--text'>" + file.name + "</div><div class='file__value--remove' data-id='" + file.name + "' ></div></div>").insertAfter($(this).parents('.added_service_input'));
        }
    });

});

//Click to remove item
$('body').on('click', '.logo_file_value, .added_service_images', function() {
    $('input[name="logo"]').val('');
    $(this).siblings('.added_service_input').children('.added_services_image, input[type="hidden"]').val('');
    $(this).remove();
});
