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

function modal_indicacao_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_cliente_indicacoes",
			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 zerar_sistema(id){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			zerar_sistema_2(id);
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		zerar_sistema_2(id);
	}
}

function zerar_sistema_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_zerar_sistema", 
			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 duplicar_sistema(id){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			duplicar_sistema_2(id);
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		duplicar_sistema_2(id);
	}
}

function duplicar_sistema_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_duplicar_sistema", 
			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 resetar_sistema(id){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			resetar_sistema_2(id);
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		resetar_sistema_2(id);
	}
}

function resetar_sistema_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_resetar_sistema", 
			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 modal_saque(id){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			modal_saque_2(id);
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		modal_saque_2(id);
	}
}

function modal_saque_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_saque_indicacoes", 
			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_indicacoes_adm",
			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= 'abrir_cliente?id="+json[i].id+"' class='btn btn-default text-blue' title='Clique para visualizar o sistema do cliente.'><i class='fa fa-user'></i></a>  <a href= 'javascript:void(0);' onclick='modal_indicacao("+json[i].id+");' class='btn btn-default text-yellow' title='Clique para editar o sistema de indicações do cliente.'><i class='fa fa-smile-o'></i></a><button type='button' class='btn btn-default dropdown-toggle' title='Clique para visualizar informações avançadas do usuário.' data-toggle='dropdown' aria-expanded='false'><span class='caret'></span><span class='sr-only'>Exibir Opções</span></button><ul class='dropdown-menu' role='menu'><li><a href='javascript:void(0);' onclick='zerar_sistema("+json[i].id+");'>Zerar Sistema</a></li><li><a href='javascript:void(0);' onclick='resetar_sistema("+json[i].id+");'>Resetar Sistema</a></li><li><a href='javascript:void(0);' onclick='duplicar_sistema("+json[i].id+");'>Duplicar Sistema</a></li>";
					if(json[i].saldowin != "R$ 0,00"){
						opcoes += "<li><a href='javascript:void(0);' onclick='modal_saque("+json[i].id+");'>Solicitar Saque</a></li>";
					}
					opcoes += "</ul></div>";
					table_data[i] = ["",json[i].nome,json[i].id, json[i].login, json[i].saldowin, json[i].saldoind, json[i].bonuspagos,json[i].bonuspendentes, opcoes, json[i].acesso, json[i].nomeempresa, json[i].ramo];
				}
				$(document).ready(function() {
					const colunas = [{},{"title": "Nome do Sistema"}, {"title": "ID"}, {"title": "Login"}, {"title": "Saldo da Win7"},{"title": "Saldo dos Ind."},{"title": "Bônus Pagos"},{"title": "Bônus Pend."},{"title": "Opções", "className": "table-buttons"},{"title": "Último Acesso"},{"title": "Nome da Empresa"}];
					$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
					$('#tabelaClientes').html('<table id="tbClientes" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
					if(json.length >= 2){
						$("#tbClientes").append(
							$('<tfoot style="display: table-header-group;" />').append(`<tr>${colunas.map((i) => "<th></th>").join("")}</tr>`)
						);
						$('#tbClientes tfoot tr th').each(function (index) {
							if(index !== 8){
								$(this).html('<input type="text" style="width: 100%" class="form-control" placeholder="" />');
							}
						});
					}
					$('#tbClientes').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 Sistema</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([3,5,6])
							//	.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,7,8,9,10])
								.every(function () {
									var that = this;
									$('input', this.footer()).on('keyup change clear', function () {
										if (that.search() !== this.value) {
											that.search(this.value).draw();
										}
									});
								});
						},
						"deferRender": true,
						"columnDefs": [{"targets": 8, "orderable": false},{"targets": [7,6,5,4], "type": "numeric-comma-real"}, {className: 'control', orderable: false, targets: 0, width: "5%"}],
						"createdRow": function ( row, data, index ) {
							$(row).addClass("id"+data[2]);
						}
					});
				});
			},
			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 adicionar_sistemas(json){
	var table = $('#tbClientes').DataTable();
	var newRows = [];
	for (var i=0; i < json.length; i++){
		var opcoes = "<div class='btn-group'><a href= 'abrir_cliente?id="+json[i].id+"' class='btn btn-default text-blue' title='Clique para visualizar o sistema do cliente.'><i class='fa fa-user'></i></a>  <a href= 'javascript:void(0);' onclick='modal_indicacao("+json[i].id+");' class='btn btn-default text-yellow' title='Clique para editar o sistema de indicações do cliente.'><i class='fa fa-smile-o'></i></a><button type='button' class='btn btn-default dropdown-toggle' title='Clique para visualizar informações avançadas do usuário.' data-toggle='dropdown' aria-expanded='false'><span class='caret'></span><span class='sr-only'>Exibir Opções</span></button><ul class='dropdown-menu' role='menu'><li><a href='javascript:void(0);' onclick='zerar_sistema("+json[i].id+");'>Zerar Sistema</a></li><li><a href='javascript:void(0);' onclick='resetar_sistema("+json[i].id+");'>Resetar Sistema</a></li><li><a href='javascript:void(0);' onclick='duplicar_sistema("+json[i].id+");'>Duplicar Sistema</a></li>";
		if(json[i].saldowin != "R$ 0,00"){
			opcoes += "<li><a href='javascript:void(0);' onclick='modal_saque("+json[i].id+");'>Solicitar Saque</a></li>";
		}
		opcoes += "</ul></div>";
		var dados = ["",json[i].nome,json[i].id, json[i].login, json[i].saldowin, json[i].saldoind, json[i].bonuspagos,json[i].bonuspendentes, opcoes, json[i].acesso, json[i].nomeempresa, json[i].ramo];
		newRows[i] = dados;
	}
	table.rows.add(newRows);
	table.draw(false);
}

function atualizar_indicacoes(json){
	var table = $('#tbClientes').DataTable();
	var registro = json;
	var tableRow = table.row(".id"+registro.id);
	var rowData = tableRow.data();
	if (rowData == null){
		return;
	}
	if(registro.hasOwnProperty('nome')) rowData[1] = registro.nome;
	if(registro.hasOwnProperty('bonuspendentes')) rowData[7] = registro.bonuspendentes;
	if(registro.hasOwnProperty('bonuspagos')) rowData[6] = registro.bonuspagos;
	if(registro.hasOwnProperty('saldoindicadores')) rowData[5] = registro.saldoindicadores;
	if(registro.hasOwnProperty('saldowin')) rowData[4] = registro.saldowin;
	tableRow.data(rowData);
	tableRow.invalidate();
	table.draw(false);
}

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

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

atualizar();

$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
$('#tabelaClientes').html('<table id="tbClientes" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
$('#tbClientes').dataTable({
	"data": [],
	"order": [[ 1, 'desc' ]],
	"columns": [{"title": "Nome do Sistema"}, {"title": "ID"}, {"title": "Login"}, {"title": "Saldo da Win7"},{"title": "Saldo dos Ind."},{"title": "Bônus Pagos"},{"title": "Bônus Pend."},{"title": "Opções", "className": "table-buttons"},{"title": "Último Acesso"},{"title": "Nome da Empresa"}],
	"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "todas"]],
	responsive: true,
	"columnDefs": [{"targets": 5, "orderable": false}]
});