$.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": [[ 3, 'desc' ],[ 2, 'desc' ]],
	"columns": [{"title": "Nome"}, {"title": "Valor"}, {"title": "Data", "class": "center"},{"title": "Status"},{"title": "Telefone"}, {"title": "Opções"}, {"title": "Pesquisa"}],
	"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "Mostrar Tudo"]],
	responsive: true,
	"columnDefs": [{"targets": 5, "orderable": false}, {"targets": 6, "visible": false}]
});

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

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

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

function modal_financeiro_confirmar_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_financeiro_confirmar",
			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_linhas(json){
	var table = $('#tbIndicacoes').DataTable();
	var table2 = $('#tbPremios').DataTable();
	for (var i=0; i < json.length; i++){
		var registro = json[i];
		var tableRow = table.row(".idindicador"+registro.id);
		var rowData = tableRow.data();
		var tableRow2 = table2.row(".idindicador"+registro.id);
		var rowData2 = tableRow2.data();
		tableRow.data(rowData);
		tableRow.invalidate();
		tableRow2.data(rowData2);
		tableRow2.invalidate();
	}
	table.draw(false);
	table2.draw(false);
}

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

function carregar_dados(){
	$(document).ready(function() {
		var dados = jQuery('#formIndicacoes').serialize();
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_indicacoes_financeiro",
			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 table_data2 = [];

				for (var i=0; i < json[1].length; i++){
					var date = Date.parse(json[1][i].data).toString('dd/MM/yyyy HH:mm:ss');
					var editar = "";
					if(json[1][i].status == "Pendente"){
						editar += "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_financeiro_confirmar("+json[1][i].id+")' class='btn btn-default text-green' title='Clique para confirmar o pagamento.'><i class='fa fa-check'></i></a><button type='button' class='btn btn-default dropdown-toggle' title='Clique para visualizar mais opçõ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'><li><a href='javascript:void(0);' onclick='modal_financeiro_deletar("+json[1][i].id+")'>Cancelar Pagamento</a></li></ul></div>";
					}
					else{
						editar += "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_editar("+json[1][i].idindicador+")' class='btn btn-default text-orange' title='Clique para editar o contato.'><i class='fa fa-edit'></i></a></div>";
					}

					table_data[i] = ["",json[1][i].nome, json[1][i].cpf, json[1][i].valor, date, json[1][i].status,json[1][i].telefone, editar, json[1][i].email, json[1][i].pesquisa, json[1][i].id, json[1][i].idindicador];
				}

				for (var i=0; i < json[2].length; i++){
					var date = Date.parse(json[2][i].data).toString('dd/MM/yyyy HH:mm:ss');
					var editar = "";
					if(json[2][i].status == "Pendente"){
						editar += "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_financeiro_confirmar("+json[2][i].id+")' class='btn btn-default text-green' title='Clique para confirmar o pagamento.'><i class='fa fa-check'></i></a><button type='button' class='btn btn-default dropdown-toggle' title='Clique para visualizar mais opçõ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'><li><a href='javascript:void(0);' onclick='modal_editar("+json[2][i].idindicador+")'>Visualizar Indicador</a></li><li><a href='javascript:void(0);' onclick='modal_financeiro_deletar("+json[2][i].id+")'>Cancelar Pagamento</a></li></ul></div>";
					}
					else{
						editar += "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_editar("+json[2][i].idindicador+")' class='btn btn-default text-orange' title='Clique para visualizar o indicador.'><i class='fa fa-edit'></i></a></div>";
					}

					table_data2[i] = ["",json[2][i].nome, json[2][i].cpf, json[2][i].premio, date, json[2][i].status,json[2][i].telefone, editar, json[2][i].email, json[2][i].pesquisa, json[2][i].id, json[2][i].idindicador];
				}

				$('#saldoindicadores').html(json[0]['saldoindicadores']);
				$('#bonuspagos').html(json[0]['bonuspagos']);
				$('#bonuspendentes').html(json[0]['bonuspendentes']);
				$('#saldowin').html(json[0]['saldowin']);
				$('#premiosentregues').html(json[0]['premiosentregues']);
				$('#premiospendentes').html(json[0]['premiospendentes']);
				
				$(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": [[ 5, 'desc' ],[ 4, 'desc' ]],
						"columns": [{},{"title": "Nome do Beneficiado"}, {"title": "CPF/CNPJ"}, {"title": "Valor"}, {"title": "Data"},{"title": "Status"},{"title": "Telefone"}, {"title": "Opções", "className": "table-buttons"}, {"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 Resgate</b></span>';
						            }
						        } ),
						        renderer: function ( api, rowIdx, columns ) {
						        	text = "";
						        	text += columns[6].data + "<br>";
						        	for(i = 0;i < columns.length;i++){
						        		column = columns[i];
						        		if(i == 6) { continue; }
						        		if(i > 0) text += "<br>";
						        		text += "<b>" + column.title + ": </b>" + column.data;
						        	}
						        	return text;
						        }
						    }
						},
						"deferRender": true,
						"columnDefs": [{"targets": 7, "orderable": false}, {"targets": [3,8], "type": "numeric-comma-real"}, {className: 'control', orderable: false, targets: 0, width: "5%"}],
						"createdRow": function ( row, data, index ) {
							$(row).addClass("id"+data[11]);
							$(row).addClass("idindicador"+data[12]);
						}
					});

					$('#tabelaPremios').html('<table id="tbPremios" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
					$('#tbPremios').dataTable({
						"data": table_data2,
						"order": [[ 5, 'desc' ],[ 4, 'desc' ]],
						"columns": [{},{"title": "Nome do Beneficiado"}, {"title": "CPF/CNPJ"}, {"title": "Prêmio"}, {"title": "Data"},{"title": "Status"},{"title": "Telefone"}, {"title": "Opções", "className": "table-buttons"}, {"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 Resgate</b></span>';
						            }
						        } ),
						        renderer: function ( api, rowIdx, columns ) {
						        	text = "";
						        	text += columns[6].data + "<br>";
						        	for(i = 0;i < columns.length;i++){
						        		column = columns[i];
						        		if(i == 6) { continue; }
						        		if(i > 0) text += "<br>";
						        		text += "<b>" + column.title + ": </b>" + column.data;
						        	}
						        	return text;
						        }
						    }
						},
						"deferRender": true,
						"columnDefs": [{"targets": 7, "orderable": false}, {"targets": [8], "type": "numeric-comma-real"}, {className: 'control', orderable: false, targets: 0, width: "5%"}],
						"createdRow": function ( row, data, index ) {
							$(row).addClass("id"+data[11]);
							$(row).addClass("idindicador"+data[12]);
						}
					});
				});
			},
			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 fechar_modal_confirmacao(){
	$('#modal-confirmacao').modal('hide');
}

function cancelar_status(id, json){
	if(json['idproduto'] == "-1"){
		var table = $('#tbIndicacoes').DataTable();
	}
	else{
		var table = $('#tbPremios').DataTable();
	}
	var tableRow = table.row(".id"+id);
	var rowData = tableRow.data();
	if (rowData == null){
		return;
	}
	rowData[5] = "Cancelado";
	var editar = "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_editar("+json.id+")' class='btn btn-default text-orange' title='Clique para visualizar o indicador.'><i class='fa fa-edit'></i></a></div>";
	rowData[7] = editar;
	rowData[8] = json['novosaldo'];
	tableRow.data(rowData);
	tableRow.invalidate();
	table.draw(false);
	$('#saldoindicadores').html(json['saldoindicadores']);
	$('#bonuspagos').html(json['bonuspagos']);
	$('#bonuspendentes').html(json['bonuspendentes']);
	$('#saldowin').html(json['saldowin']);
	$('#premiosentregues').html(json['premiosentregues']);
	$('#premiospendentes').html(json['premiospendentes']);
}

function confirmar_status(id, json){
	if(json['idproduto'] == "-1"){
		var table = $('#tbIndicacoes').DataTable();
	}
	else{
		var table = $('#tbPremios').DataTable();
	}
	var tableRow = table.row(".id"+id);
	var rowData = tableRow.data();
	if (rowData == null){
		return;
	}
	rowData[5] = "Pago";
	var editar = "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_editar("+json.id+")' class='btn btn-default text-orange' title='Clique para visualizar o indicador.'><i class='fa fa-edit'></i></a></div>";
	rowData[7] = editar;
	tableRow.data(rowData);
	tableRow.invalidate();
	table.draw(false);
	$('#saldoindicadores').html(json['saldoindicadores']);
	$('#bonuspagos').html(json['bonuspagos']);
	$('#bonuspendentes').html(json['bonuspendentes']);
	$('#saldowin').html(json['saldowin']);
	$('#premiosentregues').html(json['premiosentregues']);
	$('#premiospendentes').html(json['premiospendentes']);
}

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

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

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