<?php
	// Tenta se conectar ao servidor MySQL
	include $_SERVER["DOCUMENT_ROOT"].'/inc/conexao.php';
	include $_SERVER["DOCUMENT_ROOT"].'/inc/functions.php';
	$cfg = $_SESSION["configs"];

	// ini_set('display_errors',1);
	// ini_set('display_startup_erros',1);
	// error_reporting(E_ALL);

	$urlbase = $_SERVER['SERVER_NAME'].$_SERVER ['REQUEST_URI'];
	$parts = parse_url($urlbase);
	parse_str($parts['query'], $query);
	$_GET = $query;
	if(count($_POST) == 0){ $_POST = $_GET; }
	$token = $_GET["token"];
	if($token == '' && isset($_SESSION["usuario"])){ $_GET["token"] = $_SESSION["usuario"]["api_token"]; $token = $_SESSION["usuario"]["api_token"]; }

	// Verifica type e permissões
	if(!isset($_GET["token"])){ $ret['error'] = 'Token inexistente ou invalido.'; $ret['status'] = 'error'; $ret['status_code'] = 'notfoundtype'; finishJSONRequest($ret); }

	// Retorno
	$ret = array();
	$ret['date'] = date('Y-m-d H:i:s');
	$datetime = date('Y-m-d H:i:s');

	// Pesquisa usuário
	$sql = $mysqli->query("SELECT usuario_id, usuario_permissoes, usuario_nome, usuario_tipo FROM usuarios WHERE usuario_api_token = '$token'");
	if(mysqli_num_rows($sql) == 0 || !isset($_GET["token"]) || $_GET["token"] == ''){ $ret['error'] = 'TOKEN invalido.'; $ret['status'] = 'error'; $ret['status_code'] = 'notfoundtype'; finishJSONRequest($ret); }

	// Pega dados do usuario
	$u = $sql->fetch_assoc();
	$userid = $u["usuario_id"];
	$perms = explode('-', $u["usuario_permissoes"]);

	// Verifica type e permissões
	if(!in_array('22', $perms) && !in_array('23', $perms)){ $ret['error'] = 'Você não possui permissões suficientes para visualizar a apuração.'; $ret['status'] = 'error'; $ret['status_code'] = 'invalidPerm'; finishJSONRequest($ret); }

	// Todos os usuários
	$users = array();
	$sql = $mysqli->query("SELECT * FROM usuarios ORDER BY usuario_nome ASC");
	while ($t = $sql->fetch_assoc()) {
		$users[$t["usuario_id"]]["id"] = $t["usuario_id"];
		$users[$t["usuario_id"]]["nome"] = utf8_encode($t["usuario_nome"]);
		$users[$t["usuario_id"]]["gerente"] = $t["usuario_gerente"];
		$users[$t["usuario_id"]]["status"] = $t["usuario_status"];
		$users[$t["usuario_id"]]["credito"] = $t["usuario_credito"];
		$users[$t["usuario_id"]]["tipo"] = $t["usuario_tipo"];
	}

	// RECEBE VARIÁVEIS
	$ret['dates'] = $_POST["date"].' a '.$_POST["enddate"];
	$status = $_POST["status"];
	$type = $_POST["type"];
	$sort = $_POST["sort"];
	$date = explode('/', $mysqli->escape_string($_POST["date"]));
	$enddate = explode('/', $mysqli->escape_string($_POST["enddate"]));
	$date = $date[2].'-'.$date[1].'-'.$date[0];
	$enddate = $enddate[2].'-'.$enddate[1].'-'.$enddate[0];
	$level2 = $mysqli->escape_string($_POST["level2"]);
	$level3 = $mysqli->escape_string($_POST["level3"]);
	$level4 = $mysqli->escape_string($_POST["level4"]);
	$usuarioBase = $userid;
	$usuario_selecionado = 0;
	if((int)$level2 <> '0'){ $usuario_selecionado = 1; $usuarioBase = $level2; }
	if((int)$level3 <> '0'){ $usuario_selecionado = 1; $usuarioBase = $level3; }
	if((int)$level4 <> '0'){ $usuario_selecionado = 1; $usuarioBase = $level4; }

	if($usuarioBase <> $userid){ $ret['dates'] = $users[$usuarioBase]['nome'].' | '.$ret['dates']; }

	// Inicia arrays
	$lv2 = array();
	$lv3 = array();
	$lv4 = array();
	$hierarquia = array();

	// Tipos de usuários
	$usuariosPesquisa = array($usuarioBase); // Usuários que fazem parte da pesquisa

	if($usuario_selecionado == '1' || $u["usuario_tipo"] <> '1'){
		$sql = $mysqli->query("SELECT t1.usuario_id AS lev1, t2.usuario_id as lev2, t3.usuario_id as lev3, t4.usuario_id as lev4 FROM usuarios AS t1 LEFT JOIN usuarios AS t2 ON t2.usuario_gerente = t1.usuario_id LEFT JOIN usuarios AS t3 ON t3.usuario_gerente = t2.usuario_id LEFT JOIN usuarios AS t4 ON t4.usuario_gerente = t3.usuario_id WHERE t1.usuario_id = '$usuarioBase'");
	} else {
		$sql = $mysqli->query("SELECT t1.usuario_id AS lev1, t2.usuario_id as lev2, t3.usuario_id as lev3, t4.usuario_id as lev4 FROM usuarios AS t1 LEFT JOIN usuarios AS t2 ON t2.usuario_gerente = t1.usuario_id LEFT JOIN usuarios AS t3 ON t3.usuario_gerente = t2.usuario_id LEFT JOIN usuarios AS t4 ON t4.usuario_gerente = t3.usuario_id");
	}
	while($i = $sql->fetch_assoc()){

		// Para caso de administradores
		if($usuario_selecionado == '0'){
			$i['lev4'] = $i['lev3'];
			$i['lev3'] = $i['lev2'];
			$i['lev2'] = $i['lev1'];
		}

		// Hierarquias
		if(!isset($hierarquia[$usuarioBase])){ $hierarquia[$usuarioBase] = array(); }
		if(!isset($hierarquia[$i["lev2"]])){ $hierarquia[$i["lev2"]] = array(); }
		if(!isset($hierarquia[$i["lev3"]])){ $hierarquia[$i["lev3"]] = array(); }

		if((int)$i["lev2"] <> 0 && !in_array($i["lev2"], $usuariosPesquisa)){
			array_push($usuariosPesquisa, $i["lev2"]);
			array_push($lv2, $i["lev2"]);

			// Hierarquias
			$hierarquia[$usuarioBase][] = $i["lev2"];
		}

		if((int)$i["lev3"] <> 0 && !in_array($i["lev3"], $usuariosPesquisa)){
			array_push($usuariosPesquisa, $i["lev3"]);
			array_push($lv3, $i["lev3"]);

			// Hierarquias
			$hierarquia[$usuarioBase][] = $i["lev3"];
			$hierarquia[$i["lev2"]][] = $i["lev3"];
		}

		if((int)$i["lev4"] <> 0 && !in_array($i["lev4"], $usuariosPesquisa)){
			array_push($usuariosPesquisa, $i["lev4"]);
			array_push($lv4, $i["lev4"]);

			// Hierarquias
			$hierarquia[$usuarioBase][] = $i["lev4"];
			$hierarquia[$i["lev2"]][] = $i["lev4"];
			$hierarquia[$i["lev3"]][] = $i["lev4"];
		}
	}

	// Bloqueia caso consulta seja a usuário não gerenciado
	if($usuarioBase <> $userid && !getHierarquia($userid, $usuarioBase, $users) && $u["usuario_tipo"] <> '1'){ $ret['error'] = 'Este usuário não faz parte do seu gerenciamento.'; $ret['status'] = 'error'; $ret['status_code'] = 'invalidPerm'; finishJSONRequest($ret); }

	// Faz pesquisa
	$status_default = array();
	foreach ($status as $k => $v) { array_push($status_default, $v); }
	if(count($status_default) == 1 && in_array('5', $status_default)){ array_push($status, '1'); }
	$status = join("','", $status);
	$usuariosPesquisa = join("','", $usuariosPesquisa);

	// Ordenação
	switch ($sort) {
		case 'dateasc':
			$sort = 'ORDER BY cupom_data ASC';
			break;

		case 'datedesc':
			$sort = 'ORDER BY cupom_data DESC';
			break;

		case 'priceasc':
			$sort = 'ORDER BY cupom_valor ASC';
			break;

		case 'pricedesc':
			$sort = 'ORDER BY cupom_valor DESC';
			break;

		case 'returnasc':
			$sort = 'ORDER BY cupom_retorno ASC';
			break;

		case 'returndesc':
			$sort = 'ORDER BY cupom_retorno DESC';
			break;

		default:
			$sort = 'ORDER BY cupom_data DESC';
			break;
	}

	// Nome do cliente
	$client_name = $_POST["client_name"];
	if($client_name <> ''){
		$client_name = "and cupom_cliente LIKE '%$client_name%' ";
	} else { $client_name = ''; }

	if($u["usuario_tipo"] == '1' && $usuario_selecionado == 0){
		$sql = $mysqli->query("SELECT CAST(cupom_valor AS UNSIGNED) AS cupom_valor, cupom_parcial, CAST(cupom_retorno AS UNSIGNED) AS cupom_retorno, cupom_situacao, cupom_saidas, cupom_data, cupom_codigo, cupom_comissao, cupom_aovivo, cupom_cliente, cupom_usuario FROM cupons WHERE cupom_situacao IN('$status') $client_name and cupom_usuario <> '0' and cupom_data BETWEEN '$date 00:00:00' and '$enddate 23:59:59' $sort");
	} else {
		$sql = $mysqli->query("SELECT CAST(cupom_valor AS UNSIGNED) AS cupom_valor, cupom_parcial, CAST(cupom_retorno AS UNSIGNED) AS cupom_retorno, cupom_situacao, cupom_saidas, cupom_data, cupom_codigo, cupom_comissao, cupom_aovivo, cupom_cliente, cupom_usuario FROM cupons WHERE cupom_situacao IN('$status') $client_name and cupom_usuario IN('$usuariosPesquisa') and cupom_data BETWEEN '$date 00:00:00' and '$enddate 23:59:59' $sort");
	}

	$ret['qtd'] = mysqli_num_rows($sql);
	$ret['total']['open_entries'] = 0;
	$ret['total']['entries'] = 0;
	$ret['total']['rewards'] = 0;
	$ret['total']['cancelled'] = 0;
	$ret['total']['comissions'] = 0;
	$ret['total']['total'] = 0;

	// NOVO
	$byStatus['1']['entries'] = 0;
	$byStatus['1']['rewards'] = 0;
	$byStatus['1']['comissions'] = 0;
	$byStatus['1']['qtd'] = 0;
	$byStatus['1']['total'] = 0;

	$byStatus['11']['entries'] = 0;
	$byStatus['11']['rewards'] = 0;
	$byStatus['11']['comissions'] = 0;
	$byStatus['11']['qtd'] = 0;
	$byStatus['11']['total'] = 0;

	$byStatus['2']['entries'] = 0;
	$byStatus['2']['rewards'] = 0;
	$byStatus['2']['comissions'] = 0;
	$byStatus['2']['qtd'] = 0;
	$byStatus['2']['total'] = 0;

	$byStatus['3']['entries'] = 0;
	$byStatus['3']['rewards'] = 0;
	$byStatus['3']['comissions'] = 0;
	$byStatus['3']['qtd'] = 0;
	$byStatus['3']['total'] = 0;

	$byStatus['4']['entries'] = 0;
	$byStatus['4']['rewards'] = 0;
	$byStatus['4']['comissions'] = 0;
	$byStatus['4']['qtd'] = 0;
	$byStatus['4']['total'] = 0;

	// /NOVO
	$bils = array();
	while ($b = $sql->fetch_assoc()) {
		array_push($bils, $b['cupom_codigo']);
		if($b["cupom_usuario"] == '0'){ continue; }
		if(!isset($ret['byUser'][$b["cupom_usuario"]])){
			$ret['byUser'][$b["cupom_usuario"]]['id'] = $b["cupom_usuario"];
			$ret['byUser'][$b["cupom_usuario"]]['name'] = $users[$b["cupom_usuario"]]['nome'];
			$ret['byUser'][$b["cupom_usuario"]]['id_manager'] = $users[$b["cupom_usuario"]]['gerente'];
			$ret['byUser'][$b["cupom_usuario"]]['name_manager'] = $users[$users[$b["cupom_usuario"]]['gerente']]['nome'];
			$ret['byUser'][$b["cupom_usuario"]]['open_entries'] = 0;
			$ret['byUser'][$b["cupom_usuario"]]['entries'] = 0;
			$ret['byUser'][$b["cupom_usuario"]]['rewards'] = 0;
			$ret['byUser'][$b["cupom_usuario"]]['cancelled'] = 0;
			$ret['byUser'][$b["cupom_usuario"]]['comissions'] = 0;
			$ret['byUser'][$b["cupom_usuario"]]['total'] = 0;
		}

		// NOVO
		$pseudoStatus = $b['cupom_situacao'];
		$pseudoReward = ($pseudoStatus == '2') ? $b['cupom_saidas'] : 0;
		if($b['cupom_situacao'] == '1' && $b['cupom_parcial'] == '1'){ $pseudoStatus = '11'; }
		$byStatus[$pseudoStatus]['qtd']++;
		$byStatus[$pseudoStatus]['entries'] += $b['cupom_valor'];
		$byStatus[$pseudoStatus]['rewards'] += ($pseudoStatus == '2') ? $b['cupom_saidas'] : 0;
		$byStatus[$pseudoStatus]['comissions'] += $b['cupom_comissao'];
		$byStatus[$pseudoStatus]['total'] += ($b['cupom_valor'] - ($pseudoReward + $b['cupom_comissao']));
		// /NOVO

		switch ($b["cupom_situacao"]) {
			case '1':
				$ret['total']['open_entries'] += $b["cupom_valor"];
				$ret['total']['entries'] += $b["cupom_valor"];
				$ret['byUser'][$b["cupom_usuario"]]['open_entries'] += $b["cupom_valor"];
				$ret['byUser'][$b["cupom_usuario"]]['entries'] += $b["cupom_valor"];
				$ret['byUser'][$b["cupom_usuario"]]['comissions'] += $b["cupom_comissao"];
				$ret['total']['comissions'] += $b["cupom_comissao"];
				break;

			case '2':
				$ret['total']['entries'] += $b["cupom_valor"];
				$ret['total']['rewards'] += $b["cupom_saidas"];
				$ret['total']['comissions'] += $b["cupom_comissao"];
				$ret['byUser'][$b["cupom_usuario"]]['entries'] += $b["cupom_valor"];
				$ret['byUser'][$b["cupom_usuario"]]['rewards'] += $b["cupom_saidas"];
				$ret['byUser'][$b["cupom_usuario"]]['comissions'] += $b["cupom_comissao"];
				break;

			case '3':
				$ret['total']['entries'] += $b["cupom_valor"];
				$ret['total']['comissions'] += $b["cupom_comissao"];
				$ret['byUser'][$b["cupom_usuario"]]['entries'] += $b["cupom_valor"];
				$ret['byUser'][$b["cupom_usuario"]]['comissions'] += $b["cupom_comissao"];
				break;

			case '4':
				$ret['total']['cancelled'] += $b["cupom_valor"];
				$byStatus['4']['entries'] += $b["cupom_valor"];
				$ret['byUser'][$b["cupom_usuario"]]['cancelled'] += $b["cupom_valor"];
				break;

			default:
				# code...
				break;
		}

		if($b['cupom_usuario'] == '0'){ unset($ret['coupons'][$c["cupom_codigo"]]); continue; }
		$ret['coupons'][$c["cupom_codigo"]]['code'] = ($b["cupom_codigo"]);
		$ret['coupons'][$b["cupom_codigo"]]['date'] = desfazDatetime($b["cupom_data"]);
		$ret['coupons'][$b["cupom_codigo"]]['client'] = utf8_encode($b["cupom_cliente"]);
		$ret['coupons'][$b["cupom_codigo"]]['seller'] = utf8_encode($users[$b["cupom_usuario"]]['nome']);
		$ret['coupons'][$b["cupom_codigo"]]['price'] = formataReal($b["cupom_valor"]);
		$ret['coupons'][$b["cupom_codigo"]]['return'] = formataReal($b["cupom_retorno"]);
		$ret['coupons'][$b["cupom_codigo"]]['live'] = ($b["cupom_aovivo"]);
		$ret['coupons'][$b["cupom_codigo"]]['comission'] = formataReal($b["cupom_comissao"]);
		$ret['coupons'][$b["cupom_codigo"]]['rewards'] = formataReal($b["cupom_saidas"]);
		$ret['coupons'][$b["cupom_codigo"]]['status'] = ($b["cupom_situacao"]);
		if($b["cupom_situacao"] == '1' && $b["cupom_parcial"] == '1'){ $ret['coupons'][$b["cupom_codigo"]]['status'] = '11'; }
	}

	$bets = array();
	if(isset($_POST['show_bets'])){
		$bils = join("','", $bils);
		$sql = $mysqli->query("SELECT aposta_codigo, aposta_cupom, aposta_jogo_nome, aposta_opcao, aposta_mercado, aposta_status FROM apostas WHERE aposta_cupom IN('$bils')");
		while ($a = $sql->fetch_assoc()) {
			$iaux = count($bets[$a['aposta_cupom']]);
			$bets[$a['aposta_cupom']][$iaux]['name'] = utf8_encode($a['aposta_jogo_nome']);
			$bets[$a['aposta_cupom']][$iaux]['option'] = utf8_encode($a['aposta_opcao']);
			$bets[$a['aposta_cupom']][$iaux]['market'] = utf8_encode($a['aposta_mercado']);
			$bets[$a['aposta_cupom']][$iaux]['status'] = utf8_encode($a['aposta_status']);
			$bets[$a['aposta_cupom']][$iaux]['live'] = ($a["aposta_codigo"] == 'aovivo') ? '1' : '0';
		}
	}

	// LANÇAMENTOS
	$ret['total']['lanc'] = 0;
	$lancamentos = array();
	$sql2 = $mysqli->query("SELECT * FROM lancamentos WHERE lancamento_data BETWEEN '$date 00:00:00' AND '$enddate 23:59:59'");

	while ($l = $sql2->fetch_assoc()) {

		// Confere se lançamento procede
		if((int)$usuarioBase <> '0' && $type == 'general' && $usuarioBase <> $l["lancamento_usuario"] && getHierarquia($usuarioBase, $l["lancamento_usuario"], $_SESSION["users"]) == false){ continue; }

		if($l["lancamento_tipo"] == 'C'){
			$ret['total']['lanc'] += $l["lancamento_valor"];
			$lancamentos[$l["lancamento_usuario"]] += $l["lancamento_valor"];
		} else {
			$ret['total']['lanc'] -= $l["lancamento_valor"];
			$lancamentos[$l["lancamento_usuario"]] -= $l["lancamento_valor"];
		}
	}

	// Total
	$ret['total']['total'] += (($ret['total']['entries'] + $ret['total']['lanc']) - ($ret['total']['rewards'] + $ret['total']['comissions']));

	// Formata
	$ret['total']['open_entries'] = formataReal($ret['total']['open_entries']);
	$ret['total']['entries'] = formataReal($ret['total']['entries']);
	$ret['total']['rewards'] = formataReal($ret['total']['rewards']);
	$ret['total']['cancelled'] = formataReal($ret['total']['cancelled']);
	$ret['total']['comissions'] = formataReal($ret['total']['comissions']);
	$ret['total']['total'] = formataReal($ret['total']['total']);


	// Adiciona valores vindos da hierarquia
	foreach ($hierarquia as $k => $h2) {
		if(count($h2) == 0){ continue; }
		foreach ($h2 as $h) {
			if(!isset($ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k])){
				$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['id'] = $k;
				$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['name'] = $users[$k]['nome'];
				$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['id_manager'] = $users[$k]['gerente'];
				$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['name_manager'] = $users[$users[$k]['gerente']]['nome'];
				$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['open_entries'] = $ret['byUser'][$k]['open_entries'];
				$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['entries'] = $ret['byUser'][$k]['entries'];
				$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['rewards'] = $ret['byUser'][$k]['rewards'];
				$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['cancelled'] = $ret['byUser'][$k]['cancelled'];
				$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['comissions'] = $ret['byUser'][$k]['comissions'];
				$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['total'] = (($ret['byUser'][$k]['entries']) - ($ret['byUser'][$k]['rewards'] + $ret['byUser'][$k]['comissions']));
			}

			$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['open_entries'] += ($ret['byUser'][$h]['open_entries']);
			$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['entries'] += ($ret['byUser'][$h]['entries']);
			$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['rewards'] += ($ret['byUser'][$h]['rewards']);
			$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['cancelled'] += ($ret['byUser'][$h]['cancelled']);
			$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['comissions'] += ($ret['byUser'][$h]['comissions']);
			$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['total'] += (($ret['byUser'][$h]['entries']) - ($ret['byUser'][$h]['rewards'] + $ret['byUser'][$h]['comissions']));
		}

		// Correção BUG
		if($k == $userid){
			$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['open_entries'] /= 2;
			$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['entries'] /= 2;
			$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['rewards'] /= 2;
			$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['cancelled'] /= 2;
			$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['comissions'] /= 2;
			$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['total'] /= 2;
		}

		$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['open_entries'] = formataReal($ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['open_entries']);
		$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['entries'] = formataReal($ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['entries']);
		$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['rewards'] = formataReal($ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['rewards']);
		$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['cancelled'] = formataReal($ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['cancelled']);
		$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['comissions'] = formataReal($ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['comissions']);
		$ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['total'] = formataReal($ret['byManager'][$_SESSION["tipos_usuarios"][$users[$k]['tipo']]['nome']][$k]['total']);
	}

	foreach ($ret['byUser'] as $k => $v) {
		$ret['byUser'][$k]['lanc'] = (isset($lancamentos[$k])) ? ($lancamentos[$k]) : '0';
		$ret['byUser'][$k]['total'] += (($ret['byUser'][$k]['entries'] + $ret['byUser'][$k]['lanc']) - ($ret['byUser'][$k]['rewards'] + $ret['byUser'][$k]['comissions']));
		$ret['byUser'][$k]['open_entries'] = formataReal($ret['byUser'][$k]['open_entries']);
		$ret['byUser'][$k]['entries'] = formataReal($ret['byUser'][$k]['entries']);
		$ret['byUser'][$k]['rewards'] = formataReal($ret['byUser'][$k]['rewards']);
		$ret['byUser'][$k]['cancelled'] = formataReal($ret['byUser'][$k]['cancelled']);
		$ret['byUser'][$k]['comissions'] = formataReal($ret['byUser'][$k]['comissions']);
		$ret['byUser'][$k]['lanc'] = formataReal($ret['byUser'][$k]['lanc']);
		$ret['byUser'][$k]['balance_type'] = ($ret['byUser'][$k]['total'] <= 0) ? '-' : '+';
		$ret['byUser'][$k]['total'] = formataReal($ret['byUser'][$k]['total']);
	}

	if(isset($ret['byManager']['Administradores'])){ unset($ret['byManager']['Administradores']); }
	$ret['status'] = 'success';
	$ret['success'] = 'Pronto!';

	if($type <> 'detailed'){ unset($ret['coupons']); }

	// TRATA INFORMAÇÕES
	$table = array();
	$itr = 0;
	$itd = 0;
	switch ($type) {
		case 'general':
			// Titulo
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bg-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Descrição';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bg-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = '#';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bg-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Total Bruto';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bg-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Total Pago';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bg-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Comiss.';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bg-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Total Líquido';
			$itd = 0; $itr++;

			// Abertos
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-info ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = 'Aberto';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = $byStatus['1']['qtd'];
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = formataReal($byStatus['1']['entries']);
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = '0,00';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = formataReal($byStatus['1']['comissions']);
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bold ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = '<i class="fa fa-circle text-info pull-left"></i> '.formataReal($byStatus['1']['total']);
			if(!in_array('1', $_POST["status"])){ unset($table[$itr]); }
			else { $itd = 0; $itr++; }

			// Abertos
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-warning ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = 'Process. Parcial';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = $byStatus['11']['qtd'];
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = formataReal($byStatus['11']['entries']);
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = '0,00';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = formataReal($byStatus['11']['comissions']);
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bold ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = '<i class="fa fa-circle text-warning pull-left"></i> '.formataReal($byStatus['11']['total']);
			if(!in_array('5', $_POST["status"])){ unset($table[$itr]); }
			else { $itd = 0; $itr++; }

			// Ganhou
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-success ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = 'Ganho';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = $byStatus['2']['qtd'];
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = formataReal($byStatus['2']['entries']);
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = formataReal($byStatus['2']['rewards']);
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = formataReal($byStatus['2']['comissions']);
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bold ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = '<i class="fa fa-circle text-success pull-left"></i> '.formataReal($byStatus['2']['total']);
			if(!in_array('2', $_POST["status"])){ unset($table[$itr]); }
			else { $itd = 0; $itr++; }

			// Perdido
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-danger ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = 'Perdido';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = $byStatus['3']['qtd'];
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = formataReal($byStatus['3']['entries']);
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = '0,00';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = formataReal($byStatus['3']['comissions']);
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bold ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = '<i class="fa fa-circle text-danger pull-left"></i> '.formataReal($byStatus['3']['total']);
			if(!in_array('3', $_POST["status"])){ unset($table[$itr]); }
			else { $itd = 0; $itr++; }

			// Cancelado
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bg-dark2 ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = 'Cancelado';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = $byStatus['4']['qtd'];
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = formataReal($byStatus['4']['entries']);
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = '0,00';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = '0,00';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bold ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = '<i class="fa fa-circle pull-left"></i> '.formataReal($byStatus['4']['entries']);
			if(!in_array('4', $_POST["status"])){ unset($table[$itr]); }
			else { $itd = 0; $itr++; }


			// Lançamentos
			$table[$itr][$itd]['colspan'] = 5;
			$table[$itr][$itd]['class'] = 'ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = 'Lançamento de Caixa';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bold ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = formataReal($ret['total']['lanc']);
			$itd = 0; $itr++;

			// Total
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'bold ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = 'Total';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = ($byStatus['1']['qtd'] + $byStatus['11']['qtd'] + $byStatus['2']['qtd'] + $byStatus['3']['qtd']);
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = ($ret['total']['entries']);
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = '0,00';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = '';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = ($ret['total']['comissions']);
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = ((int)$ret['total']['total'] > 0) ? 'text-green bold ff' : 'text-red bold ff';
			$table[$itr][$itd]['type'] = 'td';
			$table[$itr][$itd]['align'] = 'center';
			$table[$itr][$itd]['html'] = ($ret['total']['total']);
			$itd = 0; $itr++;
			break;

		case 'user':
			// Titulo
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Usuário';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Total Bruto';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Total Pago';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Comiss.';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Lançamento Caixa';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Cancelamentos';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Total Líquido';
			$itd = 0; $itr++;

			foreach ($ret['byUser'] as $k => $v) {
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = 'bold';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = '';
				$table[$itr][$itd]['html'] = $v['name'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['entries'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['rewards'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['comissions'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = (isset($lancamentos[$k])) ? formataReal($lancamentos[$k]) : '0,00';
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['cancelled'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = ((int)$v['total'] > 0) ? 'btn-success' : 'btn-danger';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['total'];
				$itd = 0; $itr++;
			}
			break;

		case 'manager':
			// Titulo
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Supervisor';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Total Bruto';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Total Pago';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Comiss.';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Cancel.';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Total Líquido';
			$itd = 0; $itr++;

			foreach ($ret['byManager']['Supervisores'] as $k => $v) {
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = 'bold';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = '';
				$table[$itr][$itd]['html'] = $v['name'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['entries'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['rewards'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['comissions'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['cancelled'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = ((int)$v['total'] > 0) ? 'btn-success' : 'btn-danger';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['total'];
				$itd = 0; $itr++;
			}
			break;

		case 'manager2':
			// Titulo
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Supervisor';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Total Bruto';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Total Pago';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Comiss.';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Cancel.';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Total Líquido';
			$itd = 0; $itr++;

			foreach ($ret['byManager']['Gerentes'] as $k => $v) {
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = 'bold';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = '';
				$table[$itr][$itd]['html'] = $v['name'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['entries'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['rewards'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['comissions'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['cancelled'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = ((int)$v['total'] > 0) ? 'btn-success' : 'btn-danger';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['total'];
				$itd = 0; $itr++;
			}
			break;

		case 'detailed':
			// Titulo
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Código';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';

			if(!isset($_POST['show_bets'])){
				$table[$itr][$itd]['html'] = 'Cliente';
			} else {
				$table[$itr][$itd]['html'] = 'Detalhes';
			}
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Data';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Cambista';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Valor';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Comissão';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Retorno';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Status';
			$itd++;
			$table[$itr][$itd]['colspan'] = 1;
			$table[$itr][$itd]['class'] = 'btn-dark';
			$table[$itr][$itd]['type'] = 'th';
			$table[$itr][$itd]['align'] = '';
			$table[$itr][$itd]['html'] = 'Opções';
			$itd = 0; $itr++;
			$i = 0;
			foreach ($ret['coupons'] as $k => $v) {
				if($k == ''){ continue; }
				$pct = (realToCents($v['price']) / 100);
				$pct = realToCents($v['comission']) / $pct;
				$pct = $pct * 1;
				$pct = number_format($pct);
				$code = $k;

				$i++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = '<a data-code="'.$k.'" class="btn btn-default btn-md btn-flat" href="/bilhetes/conferir?code='.$k.'" target="_blank">'.$k.'</a>';
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				if(!isset($_POST['show_bets'])){
					$table[$itr][$itd]['align'] = 'center';
					$table[$itr][$itd]['html'] = utf8_encode($v['client']);
				} else {
					$table[$itr][$itd]['align'] = 'left';
					$table[$itr][$itd]['html'] = '';
					foreach ($bets[$k] as $k => $bv) {
						$table[$itr][$itd]['html'] .= '<div style="border-bottom: 1px dashed #CCCC; padding: 2px 0;" class="';
						if($bv['status'] == '2'){ $table[$itr][$itd]['html'] .= 'text-green'; }
						if($bv['status'] == '3'){ $table[$itr][$itd]['html'] .= 'text-red'; }
						$isLive = ($bv['live'] == '1') ? '<span class="pull-right"><i class="fa fa-circle" style="color: red;"></i> &nbsp; <b>Ao vivo</b></span>' : '';
						$table[$itr][$itd]['html'] .= '">'.$bv['name'].'<br />'.$bv['market'].': <b>'.$bv['option'].'</b> '.$isLive.'</div>';
					}
				}
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['date'];
				if($v['live'] == '1'){ $table[$itr][$itd]['html'] .= '<div><i class="fa fa-circle" style="color: red;"></i> &nbsp; <b>Ao vivo</b></div>'; }
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['seller'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['price'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = $v['comission'].' <small><b>('.$pct.'%)</b></small>';
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = ($v['status'] == '2') ? $v['rewards'] : $v['return'];
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				switch ($v['status']) {
					case '1':
						$table[$itr][$itd]['html'] = '<span id="item'.$code.'" class="badge badge-info">Aberto</span>';
						break;

					case '2':
						$table[$itr][$itd]['html'] = '<span id="item'.$code.'" class="badge badge-success">Ganhou</span>';
						break;

					case '3':
						$table[$itr][$itd]['html'] = '<span id="item'.$code.'" class="badge badge-danger">Perdeu</span>';
						break;

					case '4':
						$table[$itr][$itd]['html'] = '<span id="item'.$code.'" class="badge btn-dark">Cancelado</span>';
						break;

					default:
						$table[$itr][$itd]['html'] = '<span id="item'.$code.'" class="badge badge-warning">Indefinido</span>';
						break;
				}
				$itd++;
				$table[$itr][$itd]['colspan'] = 1;
				$table[$itr][$itd]['class'] = '';
				$table[$itr][$itd]['type'] = 'td';
				$table[$itr][$itd]['align'] = 'center';
				$table[$itr][$itd]['html'] = '<a id="cancelBtn" data-code="'.$code.'" class="btn btn-sm btn-flat btn-danger"><i class="fa fa-ban"></i></a> <a target="_blank" href="/imprimir/'.$k.'" class="btn btn-sm btn-flat btn-info"><i class="fa fa-print"></i></a>';
				$itr++;
				$itd = 0;
			}
			break;

		default:
			# code...
			break;
	}
	$ret['table'] = $table;
	echo json_encode($ret);
?>