$(document).ready(function() {
    // check all for tables
    $('#selectall').on('click', function() {
        $('.selectOne').prop('checked', this.checked);
        if (this.checked) {
            $('.tableAction').removeClass('btn disabled');
        } else {
            $('.tableAction').addClass('btn disabled');
        }
    });

    $('body').on('change', '.selectOne', function() {
        var check = ($('.selectOne:checked').length == $('.selectOne').length);
        $('#selectall').prop("checked", check);
        if ($('.selectOne:checked').length) {
            $('.tableAction').removeClass('btn disabled');
        } else {
            $('.tableAction').addClass('btn disabled');
        }
    });
});


// $('.datepicker').datepicker({
//     dateFormat: 'yy/mm/dd'
// })

/**
 * For date_from and date to
 * @param date_from selector
 * @param date_to selector
 */
function installDateRangeFields(date_from, date_to) {
    $(date_from).datepicker({
        dateFormat: 'yy/mm/dd',
        onSelect: function(){
            console.clear()
            console.log($(this).datepicker('getDate'))
            console.log($(date_to).datepicker('getDate'))
            $(date_to).datepicker( "option",'minDate', $(this).datepicker('getDate'));
        }
    });

    $(date_to).datepicker({
        dateFormat: 'yy/mm/dd',
        onSelect: function(){
            console.clear()
            console.log($(this).datepicker('getDate'))
            $(date_from).datepicker( "option", 'maxDate', $(this).datepicker('getDate'));
        }
    });

}

/**
 * To set the logic of date_from , date_to range
 */
// installDateRangeFields('.date_from', '.date_to')

/**
 * get inuts and select values in given selector
 * @param string:  element identifier
 * @param string: type ['json', 'serialize']
 * @return string or json object depondes on the type
 */
function dataInDiv (element, type){
    let data={};
    $(element).find('input, select, textarea').each(function(){
        if( $(this).attr('name')){
            data[$(this).attr('name')]=$(this).val();
        }
    });

    if ('string' == type) {
        return ($.param(data));
    } else {
        return (data);

    }
}

/**
 * ajax requests handler
 *
 * object of options contains the url, data to send, headers
 */
const ajax= async (options) => {
    // console.log('options',options)
    try{
      let data=options.data,
      method=options.method?options.method:'post',
      config={
        method:method,
        url:options.url,
      }

      if(options.method=='get'){
        config.params=data
      }else{
        config.data=data
      }
      if(options.showLoading){
          $('.loading').show();
      }
      // console.log('config',config)
      const response= await axios(config);
      if(options.showLoading){
          $('.loading').hide();
      }
      if(response.status==200){
        return response.data;
      }

      let message=response.data&&response.data.message?response.data.message: 'internetConnectionProblem'
      alert(message)
      return false;
    } catch ({response: {data}}) {

        if(options.showLoading){
            $('.loading').hide();
        }
        // console.log('error ',{data})

        let message= data.message || 'Request Error'

        // console.log('errors ',  data.errors)

        if(data.errors && Object.keys(data.errors).length) {
            message= data.errors[Object.keys(data.errors)[0]]
        }

        if($('.ajaxErrorResponse').length ){
            $('.ajaxErrorResponse').html(message).fadeIn(500)
            setTimeout(() => {
                // $('.ajaxErrorResponse').fadeOut(500)
            }, 1000);
        } else {
            alert(message)
        }

        return false;
    }
};

/**
 * Data table handler
 */

 // alert("{{ csrf_token() }}")
$(document).ready(function () {
    /**
     * ajax requests handler
     *
     * object of options contains the url, data to send, headers
     */
    const ajax= async (options) => {
        // console.log('options',options)
        try{
            let data=options.data,
                method=options.method?options.method:'post',
                config={
                    method:method,
                    url:options.url,
                    onUploadProgress: function (progressEvent) {

                    },
                    onDownloadProgress: function (progressEvent) {

                    },
                }

            if(options.method=='get'){
                config.params=data
            }else{
                config.data=data
            }
            $('.loading').show();
            // console.log('config',config)
            const response= await axios(config);
            $('.loading').hide();
            if(response.status==200){
                return response.data;
            }

            let message=response.data&&response.data.message?response.data.message: 'internetConnectionProblem'
            //   alert(message)
            return false;
        } catch ({response: {data}}) {

            $('.loading').hide();

            console.log('error ',{data})

            $('.ajaxErrorResponse').html(data.message || 'Request Error').fadeIn(500)
            setTimeout(() => {
                // $('.ajaxErrorResponse').fadeOut(500)
            }, 1000);

            return false;
        }
    };

    $(document).on('click', '.resend_code', async function(e) {
        e.preventDefault();
        $('.code').val('')
        $('.verify_button').attr('disabled', true).addClass("gray");
        $('.loading').fadeIn(200);

        const url = $(this).attr('href');
        let data= {'email': $('input[name="email"]').val(), 'type': $(this).data('type')};

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

        if (response && response.message) {
            $('.ajaxResponse').removeClass('d-none').html(response.message).fadeIn(500);
            setTimeout(() => {
                $('.ajaxResponse').fadeOut(500)
            }, 3000);
        }
    });

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

        $('.loading').fadeIn(200);

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


        const response=await ajax({
            url,
            data,
            method
        });

        if (response) {
            if (response.status === 0) {
                $('.ajaxErrorResponse').removeClass('d-none').html(response.error).fadeIn(500);
                setTimeout(() => {
                    $('.ajaxErrorResponse').fadeOut(500)
                }, 3000);
            } else {
                $('.ajaxResponse').removeClass('d-none').html(response.message).fadeIn(500);
                setTimeout(() => {
                    $('.ajaxResponse').fadeOut(500);
                    window.location.href = response.url;
                }, 1000);
            }
        }
    });

    $(document).on('change', 'select.register_select', async function() {

        if (!$(this).data('target') || $(this).val() === ''){
            return  false
        }
        let url = "getLocationInfo",
            method = 'get',
            id = $(this).val(),
            foreign_id = $(this).attr('name')+'_id',
            table =  $(this).data('table'),
            table_id =  $(this).data('target')+'_id',
            data = {id:id , table: table, foreign_id:foreign_id, table_id: table_id};
        const response=await ajax({
            url,
            dataType: 'html',
            data,
            method
        });

        if (response) {
            $('.'+$(this).data('target')).html(response);
        }
    });

    $(document).on('change', 'select.profile_select_region', async function() {

        if (!$(this).data('target') || $(this).val() === ''){
            return  false
        }

        let url = "getLocationInfo",
            method = 'get',
            id = $(this).val(),
            foreign_id = $(this).attr('name')+'_id',
            table =  $(this).data('table'),
            table_id =  $(this).data('target')+'_id',
            data = {id:id , table: table, foreign_id:foreign_id, table_id: table_id};
        const response=await ajax({
            url,
            dataType: 'html',
            data,
            method
        });

        alert(response)

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



});


