$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
$('#tabelaAdmins').html('<table id="tbAdmins" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
$('#tbAdmins').dataTable({
	"data": [],
	"order": [[ 1, 'desc' ]],
	"columns": [{"title": "Nome"},{"title": "ID"}, {"title": "Login"}, {"title": "Último Acesso"}, {"title": "Email"},{"title": "WhatsApp Business"},{"title": "Super Admin"}, {"title": "Opções", "className": "table-buttons"}],
	"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "todas"]],
	responsive: true,
	"columnDefs": [{"targets": 7, "orderable": false}],
	"deferRender": true
});

function modalNovoAdministrador(){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			modalNovoAdministrador_2();
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		modalNovoAdministrador_2();
	}
}

function modalNovoAdministrador_2(){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_novo_admin",
			success: function(data){
				$('.preloader').css({display:"none"});
				if(data == '-1') {window.location.href = "./"; return;}
				if(data.substring(0,2) == "-2") {toastr.clear(); toastr.error(data.substring(2)); return;}
				$('#modal-sistema-conteudo').html(data);
				$('#modal-sistema').modal();
			},
			beforeSend: function(){
				$('.preloader').css({display:"block"});
			},
			complete: function(){
				$('.preloader').css({display:"none"});
			},
			error: function(){
				$('.preloader').css({display:"none"});
				toastr.clear(); toastr.error("Houve um erro ao abrir modal."); return;
			}
		});
	});
}

function modal_editar(id){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			modal_editar_2(id);
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		modal_editar_2(id);
	}
}

function modal_editar_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_admin",
			data: {'id' : id},
			success: function(data){
				$('.preloader').css({display:"none"});
				if(data == '-1') {window.location.href = "./"; return;}
				if(data.substring(0,2) == "-2") {toastr.clear(); toastr.error(data.substring(2)); return;}
				$('#modal-sistema-conteudo').html(data);
				$('#modal-sistema').modal();
			},
			beforeSend: function(){
				$('.preloader').css({display:"block"});
			},
			complete: function(){
				$('.preloader').css({display:"none"});
			},
			error: function(){
				$('.preloader').css({display:"none"});
				toastr.clear(); toastr.error("Houve um erro ao abrir modal."); return;
			}
		});
	});
}

function modal_confirmacao(id){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			modal_confirmacao_2(id);
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		modal_confirmacao_2(id);
	}
}

function modal_confirmacao_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_admin_deletar",
			data: {'id' : id},
			success: function(data){
				$('.preloader').css({display:"none"});
				if(data == '-1') {window.location.href = "./"; return;}
				if(data.substring(0,2) == "-2") {toastr.clear(); toastr.error(data.substring(2)); return;}
				$('#modal-confirmacao-conteudo').html(data);
				$('#modal-confirmacao').modal();
			},
			beforeSend: function(){
				$('.preloader').css({display:"block"});
			},
			complete: function(){
				$('.preloader').css({display:"none"});
			},
			error: function(){
				$('.preloader').css({display:"none"});
				toastr.clear(); toastr.error("Houve um erro ao abrir modal."); return;
			}
		});
	});
}

function atualizar(){
	$(document).ready(function() {
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_admins",
			success: function(data){
				$('.preloader').css({display:"none"});
				if(data == '-1') {window.location.href = "./"; return;}
				if(data.substring(0,2) == "-2") {toastr.clear(); toastr.error(data.substring(2)); return;}
				var json = JSON.parse(data);
				var table_data = [];
				for (var i=0; i < json.length; i++){
					var opcoes = "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_editar("+json[i].id+");' class='btn btn-default text-orange' title='Clique para editar o administrador.'><i class='fa fa-edit'></i></a><a href= 'javascript:void(0);' onclick='modal_confirmacao("+json[i].id+")' class='btn btn-default text-red' title='Clique para deletar o administrador.'><i class='fa fa-trash'></i></a></div>";
					table_data[i] = ["",json[i].nome, json[i].id, json[i].login, json[i].acesso, json[i].email, json[i].whatsapp, json[i].superadm, opcoes];
				}
				$(document).ready(function() {
					const colunas = [{},{"title": "Nome"},{"title": "ID"}, {"title": "Login"}, {"title": "Último Acesso"}, {"title": "Email"},{"title": "WhatsApp Business"},{"title": "Super Admin"}, {"title": "Opções", "className": "table-buttons"}];
					$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
					$('#tabelaAdmins').html('<table id="tbAdmins" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
					if(json.length >= 2){
						$("#tbAdmins").append(
							$('<tfoot style="display: table-header-group;" />').append(`<tr>${colunas.map((i) => "<th></th>").join("")}</tr>`)
						);
						$('#tbAdmins tfoot tr th').each(function (index) {
							if(index !== 8){
								$(this).html('<input type="text" style="width: 100%" class="form-control" placeholder="" />');
							}
						});
					}
					$('#tbAdmins').dataTable({
						"data": table_data,
						"order": [[ 2, 'desc' ]],
						"columns": colunas,
						"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "todas"]],
						responsive: {
						    details: {
						    	type: 'column',
						        display: $.fn.dataTable.Responsive.display.modal( {
						            header: function ( row ) {
						                return '<span style="margin-right: 10px"><b>Dados do Administrador</b></span>';
						            }
						        } ),
						        renderer: function ( api, rowIdx, columns ) {
						        	text = "";
						        	text += columns[7].data + "<br>";
						        	for(i = 0;i < columns.length;i++){
						        		column = columns[i];
						        		if(i == 7) { continue; }
						        		if(i > 0) text += "<br>";
						        		text += "<b>" + column.title + ": </b>" + column.data;
						        	}
						        	return text;
						        }
						    }
						},
						initComplete: function () {
							// Apply the search
							this.api()
								.columns([7])
								.every(function () {
									var column = this;
                    var select = $('<select class="form-control"><option value=""></option></select>')
                        .appendTo($(column.footer()).empty())
                        .on('change', function () {
                            var val = $.fn.dataTable.util.escapeRegex($(this).val());
                            column.search(val ? '^' + val + '$' : '', true, false).draw();
                        });
                    column
                        .data()
                        .unique()
                        .sort()
                        .each(function (d, j) {
                            select.append('<option value="' + d + '">' + d + '</option>');
                        });
									var that = this;
									$('input', this.footer()).on('keyup change clear', function () {
										if (that.search() !== this.value) {
											that.search(this.value).draw();
										}
									});
									
								});
							this.api()
								.columns([0,1,2,3,4,5,6])
								.every(function () {
									var that = this;
									$('input', this.footer()).on('keyup change clear', function () {
										if (that.search() !== this.value) {
											that.search(this.value).draw();
										}
									});
								});
						},
						"columnDefs": [{"targets": 8, "orderable": false},{className: 'control', orderable: false, targets: 0, width: "5%"}],
						"createdRow": function ( row, data, index ) {
							$(row).addClass("id"+data[2]);
						},
						"deferRender": true
					});
				});
			},
			beforeSend: function(){
				$('.preloader').css({display:"block"});
			},
			complete: function(){
				$('.preloader').css({display:"none"});
			},
			error: function(){
				$('.preloader').css({display:"none"});
				toastr.clear(); toastr.error("Houve um erro ao atualizar"); return;
			}
		});
	});
}

function atualizar_linhas(json){
	var table = $('#tbAdmins').DataTable();
	for (var i=0; i < json.length; i++){
		var registro = json[i];
		var tableRow = table.row(".id"+registro.id);
		var rowData = tableRow.data();
		if (rowData == null){
			continue;
		}
		rowData[1] = registro.nome;
		rowData[3] = registro.login;
		rowData[5] = registro.email;
		rowData[6] = registro.whatsapp;
		rowData[7] = registro.superadm;
		tableRow.data(rowData);
		tableRow.invalidate();
	}
	table.draw(false);
}

function adicionar_administradores(json){
	var table = $('#tbAdmins').DataTable();
	var newRows = [];
	for (var i=0; i < json.length; i++){
		var opcoes = "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_editar("+json[i].id+");' class='btn btn-default text-orange' title='Clique para editar o administrador.'><i class='fa fa-edit'></i></a><a href= 'javascript:void(0);' onclick='modal_confirmacao("+json[i].id+")' class='btn btn-default text-red' title='Clique para deletar o administrador.'><i class='fa fa-trash'></i></a></div>";
		var dados = ["",json[i].nome, json[i].id, json[i].login, json[i].acesso, json[i].email, json[i].whatsapp, json[i].superadm, opcoes];
		newRows[i] = dados;
	}
	table.rows.add(newRows);
	table.draw(false);
}

function fechar_modal(){
	$('#modal-sistema').modal('hide');
}

function fechar_modal_confirmacao(){
	$('#modal-confirmacao').modal('hide');
}

function remover_administrador(id){
	var table = $('#tbAdmins').DataTable();
	var tableRow = table.row(".id"+id.toString());
	var rowData = tableRow.data();
	if (rowData == null){
		return;
	}
	tableRow.remove();
	table.draw(false);
}

atualizar();