<?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;
	$token = $_GET["token"];
	$type = $_GET["type"];
	$prox_segunda = date('Y-m-d', strtotime('next Monday'));
	$segunda = date('Y-m-d', strtotime('-7 days', strtotime($prox_segunda)));
	$domingo = date('Y-m-d', strtotime('-1 day', strtotime($prox_segunda)));
	$melhoresVendedores = array();
	$vendasPrejogoAovivo = array();

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

	// Datas
	if(!isset($_GET["date"])){ $date = $segunda; } else { $date = $mysqli->escape_string($_GET["date"]); }
	if(!isset($_GET["enddate"])){ $enddate = $domingo; } else { $enddate = $mysqli->escape_string($_GET["enddate"]); }
	if(!isset($_GET["type"])){ $type = $domingo; } else { $type = $mysqli->escape_string($_GET["type"]); }

	// Retorno
	$ret = array();
	$tipos_permitidos = array('personal' => 21, 'general' => 24);

	// Pesquisa usuário
	$sql = $mysqli->query("SELECT usuario_id, usuario_permissoes, usuario_nome 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(count($perms) == 0 || !in_array('10', $perms)){ $ret['error'] = 'Você não possui permissões suficientes para esta consulta. #'; $ret['status'] = 'error'; $ret['status_code'] = 'invalidPerm'; finishJSONRequest($ret); }

	// Pesquisa
	$usuarios[$userid] = utf8_encode($u["usuario_nome"]);

	// Caso haja filtro por usuário
	$user_filtro = "cupom_usuario <> '0' AND ";
	if(isset($_GET["user"])){ $user_id_filtro = (int)$_GET["user"]; $user_filtro = "cupom_usuario = '$user_id_filtro' AND "; $user_filtro2 = "lancamento_usuario = '$user_id_filtro' AND "; }

	$sql = $mysqli->query("SELECT cupom_aovivo, cupom_valor, cupom_codigo, cupom_data, cupom_cliente, cupom_retorno, cupom_usuario, cupom_comissao, cupom_saidas, cupom_situacao FROM cupons WHERE $user_filtro cupom_data BETWEEN '$date 00:00:00' AND '$enddate 23:59:59' ORDER BY cupom_data ASC");

	// Pesquisa usuários do sistema
	$sql3 = $mysqli->query("SELECT usuario_id, usuario_nome FROM usuarios");
	while ($us = $sql3->fetch_assoc()) { $usuarios[$us["usuario_id"]] = utf8_encode($us["usuario_nome"]); }


	if(!$sql){ $ret['error'] = 'Erro de consulta: '.$mysqli->error; $ret['status'] = 'error'; $ret['status_code'] = 'dbExecError'; finishJSONRequest($ret); }

	// Inicia variáveis
	$ret['charts'] = array();
	$ret['status']['1'] = 0;
	$ret['status']['2'] = 0;
	$ret['status']['3'] = 0;
	$ret['status']['4'] = 0;
	$ret['sellers'] = array();

	while ($c = $sql->fetch_assoc()) {
		###################################
		$d = explode(' ', $c["cupom_data"]);
		$d = explode('-', $d[0]);
		$d = $d[2].'/'.$d[1];
		if(!isset($ret['charts'][$d])){
			$ret['charts'][$d]['qtd'] = 0;
			$ret['charts'][$d]['live'] = 0;
			$ret['charts'][$d]['prematch'] = 0;
			$ret['charts'][$d]['cancelled'] = 0;
			$ret['charts'][$d]['sells'] = 0;
		}
		if(!isset($ret['sellers'][$c["cupom_usuario"]])){
			$ret['sellers'][$c["cupom_usuario"]]['name'] = $usuarios[$c["cupom_usuario"]];
			$ret['sellers'][$c["cupom_usuario"]]['qtd'] = 0;
		}
		###################################

		// Incrementa
		$ret['sellers'][$c["cupom_usuario"]]['qtd']++;
		$ret['status'][$c["cupom_situacao"]]++;
		$ret['charts'][$d]['qtd']++;
		$ret['charts'][$d]['sells'] += $c["cupom_valor"];
		if($c["cupom_aovivo"] == '1'){ $ret['charts'][$d]['live']++; } else { $ret['charts'][$d]['prematch']++; }
		if($c["cupom_situacao"] == '4'){ $ret['charts'][$d]['cancelled']++; }

	}

	foreach ($ret['charts'] as $k => $v) {
		$a = formataReal($v['sells']);
		$a = str_replace('.', '', $a);
		$a = str_replace(',', '.', $a);

		$ret['charts'][$k]['sells'] = $a;
	}

	// Remove simulador
	if(isset($ret['sellers']['0'])){ unset($ret['sellers']['0']); }
	usort($ret['sellers'], function($a, $b) {
	    return $b['qtd'] - $a['qtd'];
	});
	$ret['sellers'] = array_slice($ret['sellers'], 0, 5);

	$ret['dates'] = date("d/m/Y", strtotime($date)).' a '.date("d/m/Y", strtotime($enddate));
	$ret['date'] = $date;
	$ret['enddate'] = $enddate;
	echo json_encode($ret);
?>