$(".dt-initiate").each(function(index) {
	var table = $(this)
	$.each(table, function(i) {
		initiateTable(table)		
	})
})

function initiateTable(table, formData={}) {
	var columns = [];
	$.each(table.find("th"), function(i) {
		var th = $(this), 
			name = th.attr("data-column"),
			order = true,
			search = true
		if(th.is("data-order")) {
			order = false
		}
		if (th.is("data-search")) {
			search = false
		}
		columns.push({ data: name, name: name, orderable: order, searchable: search })
	});

	table.DataTable({
		processing: true,
		serverSide: true,
		ajax: {
			headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
			url: table.attr("data-url"),
			data: formData
		},
		columns: columns
	})
}

$(".dt-form-search").on("submit", function(e) {
	e.preventDefault()
	var form = $(this),
		tableSelector = form.attr('data-table-selector'),
		table = $(tableSelector),
		input = form.serializeArray(),
  		formData = input.reduce(function(acc, cur) {
	  		acc[cur.name] = cur.value
	  		return acc
	  	}, {})

  	console.log(formData)

	if ($.fn.DataTable.isDataTable(tableSelector)){
		$(tableSelector).DataTable().destroy();
	}

	initiateTable(table, formData)	
})

$(".onChangeSubmit").on("change", function() {
	$(this).closest("form").submit()
})

$(document).on("click", "a.dt-delete", function(e) {
	e.preventDefault()
	var table = $(this).closest("table")
	var url = $(this).attr("href")
	$.confirm({
		theme: 'bootstrap',
		type: 'red',
		title: Lang.get('manage.confirmation'),
		content: Lang.get('manage.delete-confirmation'),
		buttons: {
			Confirm: {
				text: Lang.get('manage.confirm'),
				action: function() {
					loading.open()
					axios.post(url)
						.then(function(response) {
							toastr.success(response.data.message)
							loading.close()
							table.DataTable().ajax.url(table.attr("data-url")).load();
						})
						.catch(function(error) {
							console.log(error)
							loading.close()
					})
				}
			},
			cancel: {
				text: Lang.get('manage.cancel'),
				action: function(){
				}
			}
		}
	})
});

$(document).on("click", "a.ajax-delete", function(e) {
	e.preventDefault()
	var url = $(this).attr("href")
	var card = $(this).closest(".thumbnail-card")
	$.confirm({
		theme: 'bootstrap',
		type: 'red',
		title: 'Confirmation',
		content: 'Delet dis?',
		buttons: {
			Confirm: {
				text: 'Confirm',
				action: function() {
					loading.open()
					axios.post(url)
						.then(function(response) {
							toastr.success(response.data.message)
							loading.close()
							card.remove()
							console.log(response)		
						})
						.catch(function(error) {
							console.log(error)
							loading.close()
					})
				}
			},
			cancel: {
				text: 'Cancel',
				action: function(){
				}
			}
		}
	})
})