<?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;
	}
}
?>
$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
$('#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": [],
	"order": [[ 3, 'desc' ]],
	"columns": [{"title": "Nome"}, {"title": "Estoque"}, {"title": "Trocas Feitas"}, {"title": "Pontos"}, {"title": "Data de Criação"}, {"title": "Imagem"},{"title": "Opções"},{"title": "ID"}],
	"columnDefs": [{"targets": 6, "orderable": false}, {"targets": 7,"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_premio_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 modalNovoPremio(){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			modalNovoPremio_2();
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		modalNovoPremio_2();
	}
}

function modalNovoPremio_2(){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_novo_premio",
			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_premio",
			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() {
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_premios",
			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++){
					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 prêmio.'><i class='fa fa-edit'></i></a><?php if($sistema->usuario->permissao_indicacoes == 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 prêmio.'><i class='fa fa-trash'></i></a><?php } ?></div>";
					var imagem = "<a href='"+json[i].link+"' target='_blank'>"+json[i].imagem+"</a>"
					table_data[i] = ["",json[i].nome, json[i].estoque, json[i].trocas, json[i].pontos, date, imagem, editar, json[i].id];
				}
				$(document).ready(function() {
					$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
					$('#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_data,
						"order": [[ 4, 'desc' ]],
						"columns": [{},{"title": "Nome"}, {"title": "Estoque"}, {"title": "Trocas Feitas"}, {"title": "Pontos"}, {"title": "Data de Criação"}, {"title": "Imagem"},{"title": "Opções", "className": "table-buttons"}],
						"columnDefs": [{"targets": 6, "orderable": false}, {className: 'control', orderable: false, targets: 0, width: "5%"}],
						"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 Prêmio</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,
						"createdRow": function ( row, data, index ) {
							$(row).addClass("id"+data[8]);
						}
					});
				});
			},
			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 = $('#tbPremios').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[1] = registro.nome;
		rowData[2] = registro.estoque;
		rowData[4] = registro.pontos;
		var imagem = "<a href='"+registro.link+"' target='_blank'>"+registro.imagem+"</a>"
		rowData[6] = imagem;
		tableRow.data(rowData);
		tableRow.invalidate();
	}
	table.draw(false);
}

function remover_premio(id){
	var table = $('#tbPremios').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_premios(json){
	var table = $('#tbPremios').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 prêmio.'><i class='fa fa-edit'></i></a><?php if($sistema->usuario->permissao_indicacoes == 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 prêmio.'><i class='fa fa-trash'></i></a><?php } ?></div>";
		var imagem = "<a href='"+json[i].link+"' target='_blank'>"+json[i].imagem+"</a>"
		var dados = ["",json[i].nome, json[i].estoque, json[i].trocas, json[i].pontos, date, imagem, editar, json[i].id];
		newRows[i] = dados;
	}
	table.rows.add(newRows);
	table.draw(false);
}

carregar_dados();