<?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="tbClientes" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
$('#tbClientes').dataTable({
	"data": [],
	"order": [[ 0, 'desc' ]],
	"columns": [{"title": "Empresa"},{"title": "ID"}, {"title": "Login"}, {"title": "Último Acesso"}, {"title": "Adwords"},{"title": "Opções", "className": "table-buttons"},{"title": "Consultoria"},{"title": "WhatsApp"},{"title": "Telefone"},{"title": "Email"},{"title": "Ramo"}],
	"columnDefs": [{"targets": 10,"visible": false},{"targets": 5, "orderable": false}],
	"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "todas"]],
	responsive: true
});

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

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

function modal_gdrive_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_cliente_gdrive",
			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('#formClientes').serialize();
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_home",
			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'><?php if($sistema->usuario->permissao_sistema_clientes != Usuario::PERM_NENHUMA){ ?><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><?php } ?> <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> <?php if($sistema->usuario->permissao_indicacoes_geral != Usuario::PERM_NENHUMA){ ?><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><?php } ?> <a href= 'javascript:void(0);' onclick='modal_gdrive("+json[i].id+");' class='btn btn-default text-green' title='Clique para editar o sistema do google drive do cliente.'><i class='fa fa-google'></i></a></div>";
					var ativo = json[i].ativo == "Sim" ? " #ativo#" : " #inativo#";
					var possuiwin7phone = json[i].possuiwin7phone == "Sim" ? "  #win7phone#" : "";
					var iconewin7 = json[i].possuiwin7phone == "Sim" ? " <i class='fa fa-phone text-green'></i>" : "";
					table_data[i] = ["",json[i].nome + iconewin7, json[i].id, json[i].login, json[i].acesso, json[i].adwords, opcoes,json[i].consultoria , json[i].whatsapp, json[i].telefone,json[i].email, json[i].ramo + ativo + possuiwin7phone];
				}
				$(document).ready(function() {
					$.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": table_data,
						"order": [[ 2, 'desc' ]],
						"columns": [{},{"title": "Empresa"},{"title": "ID"}, {"title": "Login"}, {"title": "Último Acesso"}, {"title": "Adwords"},{"title": "Opções", "className": "table-buttons"},{"title": "Consultoria"},{"title": "WhatsApp"},{"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 Cliente</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;
						        }
						    }
						},
						"columnDefs": [{"targets": 6, "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 = $('#tbClientes').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;
		}
		var ativo = registro.ativo == "Sim" ? " #ativo#" : " #inativo#";
		var possuiwin7phone = registro.possuiwin7phone == "Sim" ? "  #win7phone#" : "";
		var iconewin7 = registro.possuiwin7phone == "Sim" ? " <i class='fa fa-phone text-green'></i>" : "";
		rowData[1] = registro.nome+iconewin7;
		rowData[3] = registro.login;
		rowData[4] = registro.acesso;
		rowData[5] = registro.adwords;
		rowData[7] = registro.consultoria;
		rowData[8] = registro.whatsapp;
		rowData[9] = registro.telefone;
		rowData[10] = registro.email;
		rowData[11] = registro.ramo+ativo+possuiwin7phone;
		tableRow.data(rowData);
		tableRow.invalidate();
	}
	table.draw(false);
}

function atualizar_indicacoes(json){ return; }

function adicionar_linhas(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_editar("+json[i].id+");' class='btn btn-default text-orange' title='Clique para editar o cliente.'><i class='fa fa-edit'></i></a> <?php if($sistema->usuario->permissao_indicacoes_geral != Usuario::PERM_NENHUMA){ ?><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><?php } ?> <a href= 'javascript:void(0);' onclick='modal_gdrive("+json[i].id+");' class='btn btn-default text-green' title='Clique para editar o sistema do google drive do cliente.'><i class='fa fa-google'></i></a></div>";
		var ativo = json[i].ativo == "Sim" ? " #ativo#" : " #inativo#";
		var possuiwin7phone = json[i].possuiwin7phone == "Sim" ? "  #win7phone#" : "";
		var iconewin7 = json[i].possuiwin7phone == "Sim" ? " <i class='fa fa-phone text-green'></i>" : "";
		var dados = ["",json[i].nome+iconewin7, json[i].id, json[i].login, json[i].acesso, json[i].adwords, opcoes,json[i].consultoria , json[i].whatsapp, json[i].telefone,json[i].email, json[i].ramo+ativo+possuiwin7phone];
		newRows[i] = dados;
	}
	table.rows.add(newRows);
	table.draw(false);
}

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


$(document).ready(function(){
    $('.check-leads').change(function(){
    	var periodo = $("#data-leads").val();
        if(periodo !== "--") atualizar();
    });
    $("#data-leads").change(function(){
        var periodo = $("#data-leads").val();
        if(periodo === "personalizado")
            $('.datadiv').removeClass("hide");
        else{
            $('.datadiv').addClass("hide");
            atualizar();
		}
    });
    $('#datapersonalizada').click(function(){
        atualizar();
    });
    atualizar();
    $('.filtragem').change(function(){ atualizar(); });
});

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

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