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

	// Faz a consulta dos dados gerais do cliente
	$dados_cliente = $sistema->obter_cliente($sistema->usuario->id);
	$TXT_URL_BTN_CONTATO = $dados_cliente['TXT_URL_BTN_CONTATO'];
}
?>

$('.datepicker').datepicker({
	format: 'dd/mm/yyyy',
	endDate: '0d',
	autoclose: true,
	language: 'pt-BR'
});

$('.datepicker').mask('00/00/0000');

$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
$('#tabelaLeads').html('<table id="tbLeads" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
$('#tbLeads').dataTable({
	"data": [],
	"order": [[ 4, 'desc' ]],
	"columns": [{"title": "Nome"}, {"title": "Email"}, {"title": "Telefone"}, {"title": "Status"},{"title": "Identificador"},{"title": "Tipo"},{"title": "Data"},{"title": "Opções", "className": "table-buttons"},{"title": "Qualidade"},{"title": "Valor Fechado"},{"title": "Valor Orçado"},{"title": "ID"}],
	"columnDefs": [{"targets": 7, "orderable": false}, {"targets": 11,"visible": false}],
	"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "todas"]],
	responsive: true
});

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_contato_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 modalNovoContato(){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			modalNovoContato_2();
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		modalNovoContato_2();
	}
}

function modalNovoContato_2(){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_novo_contato",
			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_contato",
			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 carregar_dados(){
	$(document).ready(function() {
		var dados = jQuery('#formContatos').serialize();
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_contatos",
			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 = [];
				var quantidade = 0;
				var forms = 0;
				var whatsapp = 0; 
				for (var i=0; i < json.length; i++){

					const telefoneFormatado = json[i].telefone.replace(/[`~!@#$%^&*()_ |+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
					const telefoneNormal = json[i].telefone;

					const urlTelefoneFormatado = `<? echo $TXT_URL_BTN_CONTATO; ?>`.replace('#TELEFONE#',telefoneFormatado);
					const urlTelefoneNormal = `<? echo $TXT_URL_BTN_CONTATO; ?>`.replace('#TELEFONE#',telefoneNormal);

					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 editar o contato'><i class='fa fa-edit'></i></a><?php if($sistema->usuario->permissao_leads == Usuario::PERM_ESCRITA){ ?><a href= 'javascript:void(0);' onclick='modal_confirmacao(${json[i].id})' class='btn btn-default text-red' title='Clique para deletar o contato'><i class='fa fa-trash'></i></a><?php } ?> ${json[i].telefone.length > 3 ? '<a href="tel:0'+json[i].telefone.replace(/[`~!@#$%^&*()_ |+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '')+'" class="btn btn-default text-blue" title="Clique para ligar"><i class="fa fa-phone"></i></a>' : ''} ${
						json[i].telefone.length > 3 
						? json[i].tipo === 'WhatsApp' 
							? json[i].telefone.indexOf("(") != -1 
								? '<a href="'+urlTelefoneFormatado+'" class="btn btn-default text-green" target="_blank" title="Enviar mensagem para o cliente"><i class="fa fa-whatsapp"></i></a>' 
								: '<a href="'+urlTelefoneNormal+'" class="btn btn-default text-green" target="_blank" title="Enviar mensagem para o cliente"><i class="fa fa-whatsapp"></i></a>' 
							: json[i].telefone.length > 3 
								? json[i].telefone.indexOf("(") != -1 
									? '<a href="'+urlTelefoneFormatado+'" class="btn btn-default text-light-gold" target="_blank" title="Enviar mensagem para esse número"><i class="fa fa-whatsapp"></i></a>' 
									: '<a href="'+urlTelefoneNormal+'" class="btn btn-default text-light-gold" target="_blank" title="Enviar mensagem para esse número"><i class="fa fa-whatsapp"></i></a>'
								: ''
						: ''}${json[i].email.length > 0 ? '<a href="mailto:'+json[i].email+'" class="btn btn-default text-purple" target="_blank" title="Clique para enviar e-mail"><i class="fa fa-at"></i></a>' : ''}</div>`;
					
					table_data[i] = ["", json[i].nome, `<a href="mailto:${json[i].email}" style="color:#333;" title="Clique para enviar e-mail">${json[i].email}</a>`, `<a href="tel:0${json[i].telefone.replace(/[`~!@#$%^&*()_ |+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '')}" style="color:#333;" title="Clique para ligar">${json[i].telefone}</a>`, json[i].status, json[i].identificador, json[i].tipo, date, editar, json[i].qualidade, json[i].valorfechado, json[i].valororcado, json[i].id];

					quantidade++;
					if(json[i].tipo == "Formulário"){
						forms++;
					}
					else if(json[i].tipo == "WhatsApp"){
						whatsapp++;
					}
				} 
				$('#totalcontatos').html(quantidade);
				$('#whatsapp').html(whatsapp);
				$('#forms').html(forms);
				$(document).ready(function() {
					const colunas = [{},{"title": "Nome"}, {"title": "Email"}, {"title": "Telefone"}, {"title": "Status"},{"title": "Identificador"},{"title": "Tipo"},{"title": "Data"},{"title": "Opções", "className": "table-buttons"},{"title": "Qualidade"},{"title": "Valor Fechado"},{"title": "Valor Orçado"}];
					$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
					$('#tabelaLeads').html('<table id="tbLeads" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
					
					if(json.length >= 2){
						$("#tbLeads").append(
							$('<tfoot style="display: table-header-group;" />').append(`<tr>${colunas.map((i) => "<th></th>").join("")}</tr>`)
						);
						$('#tbLeads tfoot tr th').each(function (index) {
							if(index !== 8){// numero da coluna das opções
								$(this).html('<input type="text" style="width: 100%" class="form-control" placeholder="" />');
							}
						});
					}
					$('#tbLeads').dataTable({
						"data": table_data,
						"order": [[ 7, 'desc' ]],
						"columns": colunas,
						"columnDefs": [{"targets": 7, "orderable": false}, {className: 'control', orderable: false, targets: 0, width: "5%"}, 
						{
							targets: 1,
							render: function ( data, type, row ) {
								if(type=="display"){
									if($(window).width() < 600){
										if(data.length > 20){
											return data.substr( 0, 20 ) +'…';
										}
										else{
											return data;
										}
									}
								}
								return data;
							}
						}],
						initComplete: function () {
							// Apply the search
							this.api()
								.columns([4,5,6,9])
								.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,7,8,10,11])
								.every(function () {
									var that = this;
									$('input', this.footer()).on('keyup change clear', function () {
										if (that.search() !== this.value) {
											that.search(this.value).draw();
										}
									});
								});
						},
						"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[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;
						        }
						    }
						},
						"deferRender": true,
						"createdRow": function ( row, data, index ) {
							$(row).addClass("id"+data[12]);
							var current = $('td', row).eq(4);
							if(current.text() == "Fechado"){
								current.css('color','green');
							}
							else if(current.text() == "Perdeu" || current.text() == "Não é Cliente" || current.text() == "Não Compareceu"){
								current.css('color','red');
							}
							else if(current.text() == "Novo"){
								current.css('color','blue');
							}
							else if(current.text() == "Em negociação"){
								current.css('color','orange');
							}
						}
					});
				});
			},
			beforeSend: function(){
				$('.info-box-number').html('<div class="preloader"><i class="fa fa-refresh fa-spin"></i></div>');
				$('.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 = $('#tbLeads').DataTable();
	for (var i=0; i < json.length; i++){
		var registro = json[i];
		var tableRow = table.row(".id"+registro.id);
		var rowData = tableRow.data();
		//console.log(registro);

		const telefoneFormatado = registro.telefone.replace(/[`~!@#$%^&*()_ |+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
		const telefoneNormal = registro.telefone;
		
		const urlTelefoneFormatado = `<? echo $TXT_URL_BTN_CONTATO; ?>`.replace('#TELEFONE#',telefoneFormatado);
		const urlTelefoneNormal = `<? echo $TXT_URL_BTN_CONTATO; ?>`.replace('#TELEFONE#',telefoneNormal);

		if (rowData == null){
			continue;
		}
		var cell = $('td', tableRow.node()).eq(4);
		if(registro.status == "Fechado"){
			cell.css('color','green');
		}
		else if(registro.status == "Perdeu" || registro.status == "Não é Cliente"){
			cell.css('color','red');
		}
		else if(registro.status == "Novo"){
			cell.css('color','blue');
		}
		else if(registro.status == "Em negociação"){
			cell.css('color','orange');
		}
		else{
			cell.css('color','#333');
		}
		rowData[1] = registro.nome;
		rowData[2] = `<a href="mailto:${registro.email}" style="color:#333;" title="Clique para enviar e-mail">${registro.email}</a>`;
		rowData[3] = `<a href="tel:0${registro.telefone.replace(/[`~!@#$%^&*()_ |+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '')}" style="color:#333;" title="Clique para ligar">${registro.telefone}</a>`;
		rowData[4] = registro.status;
		rowData[5] = registro.identificador;
		rowData[8] = `<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_editar(${registro.id})' class='btn btn-default text-orange' title='Clique para editar o contato'><i class='fa fa-edit'></i></a><?php if($sistema->usuario->permissao_leads == Usuario::PERM_ESCRITA){ ?><a href= 'javascript:void(0);' onclick='modal_confirmacao(${registro.id})' class='btn btn-default text-red' title='Clique para deletar o contato'><i class='fa fa-trash'></i></a><?php } ?> ${registro.telefone.length > 3 ? '<a href="tel:0'+registro.telefone.replace(/[`~!@#$%^&*()_ |+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '')+'" class="btn btn-default text-blue" title="Clique para ligar"><i class="fa fa-phone"></i></a>' : ''} ${
			registro.telefone.length > 3 
			? registro.tipo === 'WhatsApp' 
				? registro.telefone.indexOf("(") != -1 
					? '<a href="'+urlTelefoneFormatado+'" class="btn btn-default text-green" target="_blank" title="Enviar mensagem para o cliente"><i class="fa fa-whatsapp"></i></a>' 
					: '<a href="'+urlTelefoneNormal+'" class="btn btn-default text-green" target="_blank" title="Enviar mensagem para o cliente"><i class="fa fa-whatsapp"></i></a>' 
				: registro.telefone.length > 3 
					? registro.telefone.indexOf("(") != -1 
						? '<a href="'+urlTelefoneFormatado+'" class="btn btn-default text-light-gold" target="_blank" title="Enviar mensagem para esse número"><i class="fa fa-whatsapp"></i></a>' 
						: '<a href="'+urlTelefoneNormal+'" class="btn btn-default text-light-gold" target="_blank" title="Enviar mensagem para esse número"><i class="fa fa-whatsapp"></i></a>'
					: ''
			: ''}${registro.email.length > 0 ? '<a href="mailto:'+registro.email+'" class="btn btn-default text-purple" target="_blank" title="Clique para enviar e-mail"><i class="fa fa-at"></i></a>' : ''}</div>`;
		rowData[9] = registro.qualidade;
		rowData[10] = registro.valorfechado;
		rowData[11] = registro.valororcado;
		tableRow.data(rowData);
		tableRow.invalidate();
	}
	table.draw(false);
}

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

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

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

function atualizar(){
	var valor = $('#data').val();
	if(valor == "CUSTOM_DATE")
		$('.datadiv').removeClass("hide");
	else{
		$('.datadiv').addClass("hide");
		carregar_dados();
		salvarFiltro(valor,'','');
	}
}

function adicionar_contatos(json){
	var table = $('#tbLeads').DataTable();
	var newRows = [];
	for (var i=0; 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 editar o contato.'><i class='fa fa-edit'></i></a><?php if($sistema->usuario->permissao_leads == Usuario::PERM_ESCRITA){ ?><a href= 'javascript:void(0);' onclick='modal_confirmacao("+json[i].id+")' class='btn btn-default text-red' title='Clique para deletar o contato.'><i class='fa fa-trash'></i></a><?php } ?></div>";
		var dados = ["",json[i].nome, json[i].email, json[i].telefone, json[i].status, json[i].identificador, json[i].tipo, date, editar, json[i].qualidade, json[i].valorfechado, json[i].valororcado, json[i].id];
		newRows[i] = dados;
	}
	table.rows.add(newRows);
	table.draw(false);
}

pegarFiltro(function(filtro,data1,data2){
	$('#data').val(filtro);
	$('#datainicial').val(data1);
	$('#datafinal').val(data2);
	if(filtro == "CUSTOM_DATE")
		$('.datadiv').removeClass("hide");
	carregar_dados();
});

$('#data, #switch').change(function(){ atualizar(); });
$('#datapersonalizada').click(function(){
	salvarFiltro($('#data').val(),$('#datainicial').val(),$('#datafinal').val());
	carregar_dados();
});