<?php 
header("Content-type: text/javascript");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

if (session_status() == PHP_SESSION_NONE) {
    require_once(__DIR__ . "/../../classes/Sistema.php");
	set_sistema(Sistema::INDICACOES);
	$sistema = new Sistema();

	if(!$sistema->sessao->logado()) {
		echo "window.location.href = './';";
		exit;
	}
}
?>
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_indicacao",
			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 editar."); return;
			}
		});
	});
}

<?php if($sistema->indicacoes->downlines == "1") { ?>

var historicoIndicadores = [[-1,[[ 4, 'desc' ]],0,25,""]];
var historicoIndex = 0;

function voltar_historico(){
	if($.active > 0) return;
	if(historicoIndex == 0) return;
	var table = $('#tbIndicacoes').DataTable();
	var dados = historicoIndicadores[historicoIndex];
	historicoIndicadores[historicoIndex] = [dados[0],table.order(),table.page(),table.page.len(),table.search()];
	historicoIndex--;
	atualizar_indicados(historicoIndicadores[historicoIndex]);
	atualizar_historico();
}

function avancar_historico(){
	if($.active > 0) return;
	if(historicoIndex == historicoIndicadores.length - 1) return;
	var table = $('#tbIndicacoes').DataTable();
	var dados = historicoIndicadores[historicoIndex];
	historicoIndicadores[historicoIndex] = [dados[0],table.order(),table.page(),table.page.len(),table.search()];
	historicoIndex++;
	atualizar_indicados(historicoIndicadores[historicoIndex]);
	atualizar_historico();
}

function home_historico(){
	if($.active > 0) return;
	if(historicoIndex == 0) return;
	var table = $('#tbIndicacoes').DataTable();
	var dados = historicoIndicadores[historicoIndex];
	historicoIndicadores[historicoIndex] = [dados[0],table.order(),table.page(),table.page.len(),table.search()];
	historicoIndex = 0;
	atualizar_indicados(historicoIndicadores[historicoIndex]);
	atualizar_historico();
}

function atualizar_historico(){
	if(historicoIndex > 0){
		$(".botao-voltar").removeClass("disabled");
		$(".botao-voltar").addClass("text-green");
	}
	else{
		$(".botao-voltar").removeClass("text-green");
		$(".botao-voltar").addClass("disabled");
	}
	if(historicoIndex < historicoIndicadores.length - 1){
		$(".botao-avancar").removeClass("disabled");
		$(".botao-avancar").addClass("text-green");
	}
	else{
		$(".botao-avancar").removeClass("text-green");
		$(".botao-avancar").addClass("disabled");
	}
	if(historicoIndicadores.length > 0 & historicoIndex > 0){
		$(".botao-home").removeClass("disabled");
		$(".botao-home").addClass("text-blue");
	}
	else{
		$(".botao-home").removeClass("text-blue");
		$(".botao-home").addClass("disabled");
	}
}

function ver_indicados(id){
	var table = $('#tbIndicacoes').DataTable();
	var dados = historicoIndicadores[historicoIndex];
	historicoIndicadores[historicoIndex] = [dados[0],table.order(),table.page(),table.page.len(),table.search()];
	historicoIndex++;
	if(historicoIndex < historicoIndicadores.length){
		historicoIndicadores = historicoIndicadores.slice(0,historicoIndex);
	}
	historicoIndicadores.push([id,table.order(),0,table.page.len(),""]);
	atualizar_historico();
	atualizar_indicados([id,table.order(),0,table.page.len(),""]);
}

function atualizar_indicados(index){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_indicados",
			data: {'id' : index[0]},
			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=1; i < json.length; i++){
					var date = Date.parse(json[i].data).toString('dd/MM/yyyy HH:mm:ss');
					var editar = "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_editar("+json[i].id+");' class='btn btn-default text-orange' title='Clique para visualizar dados do usuário.'><i class='fa fa-info-circle'></i></a>";
					var sub_str = "";
					if(json[i].sub == "1"){
						sub_str = "<li><a href='javascript:void(0);' onclick='ver_indicados("+json[i].id+");'>Visualizar Indicados</a></li>";
					}
					if(sub_str != ""){
						editar += "<button type='button' class='btn btn-default dropdown-toggle' title='Clique para visualizar mais informações.' 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'>"+sub_str+"</ul>";
					}
					editar += '</div>';
					table_data[i-1] = ["",json[i].nome, json[i].status, json[i].indicadopor, date, json[i].fechamentos, editar, json[i].telefone, json[i].email, json[i].id];
				}

				$('#indicadosDados').html(json[0]['indicadosfechados'] + "/" + json[0]['indicados']);
				$('#valorTotal').html(json[0]['saldo']);
				$('#saldoCadastro').html(json[0]['saldocadastro']);
				$(".nomeIndicado").html("<b>"+json[0]['nome']+"</b>");

				$(document).ready(function() {
					$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
					$('#tabelaIndicacoes').html('<table id="tbIndicacoes" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
					$('#tbIndicacoes').DataTable({
						"data": table_data,
						"order": index[1],
						"pageLength": index[3],
						"displayStart": index[2] * index[3],
						"search": {
							"search": index[4]
						},
						"columns": [{},{"title": "Nome"}, {"title": "Status"},{"title": "Indicado por"}, {"title": "Dia do Registro"}, {"title": "Fechamentos"},{"title": "Opções", "className": "table-buttons"}, {"title": "Telefone"}, {"title": "Email"}],
						"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 Indicado</b></span>';
						            }
						        } ),
						        renderer: function ( api, rowIdx, columns ) {
						        	text = "";
						        	text += columns[5].data + "<br>";
						        	for(i = 0;i < columns.length;i++){
						        		column = columns[i];
						        		if(i == 5) { continue; }
						        		if(i > 0) text += "<br>";
						        		text += "<b>" + column.title + ": </b>" + column.data;
						        	}
						        	return text;
						        }
						    }
						},
						"deferRender": true,
						"columnDefs": [{"targets": 6, "orderable": false},{className: 'control', orderable: false, targets: 0, width: "5%"}],
						"createdRow": function ( row, data, index ) {
							$(row).addClass("id"+data[10]);
							var current = $('td', row).eq(2);
							if(current.text() == "Fechado"){
								current.css('color','green');
							}
							else if(current.text() == "Perdeu"){
								current.css('color','red');
							}
							else if(current.text() == "Novo"){
								current.css('color','blue');
							}
						}
					});
				});
			},
			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;
			}
		});
	});
}

atualizar_indicados(historicoIndicadores[historicoIndex]);

$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
$('#tabelaIndicacoes').html('<table id="tbIndicacoes" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
$('#tbIndicacoes').DataTable({
	"data": [],
	"order": [[ 4, 'desc' ]],
	"columns": [{"title": "Nome", "class": "center"}, {"title": "Status", "class": "center"},{"title": "Indicado por", "class": "center"}, {"title": "Dia do Registro", "class": "center"}, {"title": "Fechamentos", "class": "center"}, {"title": "Opções", "class": "center"}, {"title": "Telefone"}, {"title": "Email"},{"title": "Qualidade"}],
	"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "Mostrar Tudo"]],
	responsive: true,
	"columnDefs": [{"targets": 5, "orderable": false}]
});
<?php } else { ?>

function atualizar_indicados(){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_indicados",
			data: {'id' : -1},
			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=1; i < json.length; i++){
					var date = Date.parse(json[i].data).toString('dd/MM/yyyy HH:mm:ss');
					var editar = "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_editar("+json[i].id+");' class='btn btn-default text-orange' title='Clique para visualizar dados do usuário.'><i class='fa fa-info-circle'></i></a></div>";
					table_data[i-1] = ["",json[i].nome, json[i].status, json[i].indicadopor, date, json[i].fechamentos, editar, json[i].telefone, json[i].email, json[i].id];
				}
				$('#indicadosDados').html(json[0]['indicadosfechados'] + "/" + json[0]['indicados']);
				$('#valorTotal').html(json[0]['saldo']);
				$(".nomeIndicado").html("<b>"+json[0]['nome']+"</b>");

				$(document).ready(function() {
					$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
					$('#tabelaIndicacoes').html('<table id="tbIndicacoes" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
					$('#tbIndicacoes').DataTable({
						"data": table_data,
						"order": [4,"desc"],
						"columns": [{},{"title": "Nome"}, {"title": "Status"},{"title": "Indicado por"}, {"title": "Dia do Registro"}, {"title": "Fechamentos"},{"title": "Opções", "className": "table-buttons"}, {"title": "Telefone"}, {"title": "Email"}],
						"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 Contato</b></span>';
						            }
						        } ),
						        renderer: function ( api, rowIdx, columns ) {
						        	text = "";
						        	text += columns[5].data + "<br>";
						        	for(i = 0;i < columns.length;i++){
						        		column = columns[i];
						        		if(i == 5) { continue; }
						        		if(i > 0) text += "<br>";
						        		text += "<b>" + column.title + ": </b>" + column.data;
						        	}
						        	return text;
						        }
						    }
						},
						"deferRender": true,
						"columnDefs": [{"targets": 6, "orderable": false}, {className: 'control', orderable: false, targets: 0, width: "5%"}],
						"createdRow": function ( row, data, index ) {
							$(row).addClass("id"+data[10]);
							var current = $('td', row).eq(2);
							if(current.text() == "Fechado"){
								current.css('color','green');
							}
							else if(current.text() == "Perdeu"){
								current.css('color','red');
							}
							else if(current.text() == "Novo"){
								current.css('color','blue');
							}
						}
					});
				});
			},
			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;
			}
		});
	});
}

atualizar_indicados();

$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
$('#tabelaIndicacoes').html('<table id="tbIndicacoes" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
$('#tbIndicacoes').DataTable({
	"data": [],
	"order": [[ 4, 'desc' ]],
	"columns": [{"title": "Nome", "class": "center"}, {"title": "Status", "class": "center"},{"title": "Indicado por", "class": "center"}, {"title": "Dia do Registro", "class": "center"}, {"title": "Fechamentos", "class": "center"},{"title": "Opções", "class": "center"}, {"title": "Telefone"}, {"title": "Email"}],
	"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "Mostrar Tudo"]],
	responsive: true,
	"columnDefs": [{"targets": 5, "orderable": false}]
});
<?php } ?>