<?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::WIN7_ADM);
	$sistema = new Sistema(false, false, false);

	if(!$sistema->sessao->logado()) {
		echo "window.location.href = './';";
		exit;
	}
}
?>

$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
$('#tabelaClientes').html('<table id="tblClientesImportantes" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
$('#tblClientesImportantes').dataTable({
	"data": [],
	"order": [[ 0, 'desc' ]],
	"columns": [{"title": "Empresa"},{"title": "ID"}, {"title": "Ativo"}, {"title": "Importante"}, {"title": "Opções", "className": "table-buttons"}],
	"columnDefs": [{"targets": 10,"visible": false},{"targets": 5, "orderable": false}],
	"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "todas"]],
	responsive: true
});

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_cliente_dados_bi",
			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 atualizar(){
	$(document).ready(function() {
		var dados = jQuery('#formBi').serialize();
		console.log(dados);
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_bi",
			data: dados,
			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 cliente.'><i class='fa fa-edit'></i></a></div>";
					table_data[i] = ["",json[i].nome, json[i].id, json[i].ativo ? '<span style="color: #19b919;font-weight: bold;text-transform: uppercase;">Sim</span>': '<span style="color: red">Não</span>', json[i].cli_importante ? '<span style="color: #19b919;font-weight: bold;text-transform: uppercase;">Sim</span>': '<span style="color: red">Não</span>', opcoes];
				}
				$(document).ready(function() {
					const colunas = [{},{"title": "Empresa"},{"title": "ID"}, {"title": "Ativo"}, {"title": "Importante"}, {"title": "Opções", "className": "table-buttons"}];
					$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
					$('#tabelaClientes').html('<table id="tblClientesImportantes" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
					if(json.length >= 2){
						$("#tblClientesImportantes").append(
							$('<tfoot style="display: table-header-group;" />').append(`<tr>${colunas.map((i) => "<th></th>").join("")}</tr>`)
						);
						$('#tblClientesImportantes tfoot tr th').each(function (index) {
							if(index !== 5){
								$(this).html('<input type="text" style="width: 100%" class="form-control" placeholder="" />');
							}
						});
					}
					$('#tblClientesImportantes').dataTable({
						"data": table_data,
						"order": [[ 4, '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 Cliente</b></span>';
						            }
						        } ),
						        renderer: function ( api, rowIdx, columns ) {
						        	text = "";
						        	text += columns[4].data + "<br>";
						        	for(i = 0;i < columns.length;i++){
						        		column = columns[i];
						        		if(i == 4) { continue; }
						        		if(i > 0) text += "<br>";
						        		text += "<b>" + column.title + ": </b>" + column.data;
						        	}
						        	return text;
						        }
						    }
						},
						initComplete: function () {
							// Apply the search
							//this.api()
							//	.columns([3,4])
							//	.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])
								.every(function () {
									var that = this;
									$('input', this.footer()).on('keyup change clear', function () {
										if (that.search() !== this.value) {
											that.search(this.value).draw();
										}
									});
								});
						},
						"columnDefs": [{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 = $('#tblClientesImportantes').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[3] = registro.ativo === 'Sim' ? '<span style="color: #19b919;font-weight: bold;text-transform: uppercase;">Sim</span>': '<span style="color: red">Não</span>';
		rowData[4] = registro.cli_importante === 'Sim' ? '<span style="color: #19b919;font-weight: bold;text-transform: uppercase;">Sim</span>': '<span style="color: red">Não</span>';
		tableRow.data(rowData);
		tableRow.invalidate();
	}
	table.draw(false);
}

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

$('#data, #switch').change(function () {
  atualizar();
});

$(document).ready(function(){
  atualizar();
});
