<?php
	require $_SERVER["DOCUMENT_ROOT"].'/inc/conexao.php';
    require $_SERVER["DOCUMENT_ROOT"].'/inc/functions.php';

	// Recebe parâmetros GET
	$datetime = date('Y-m-d H:i:s');
	$urlbase = $_SERVER['SERVER_NAME'].$_SERVER ['REQUEST_URI'];
	$parts = parse_url($urlbase);
	parse_str($parts['query'], $query);
	$_GET = $query;
	$token = $_GET["token"];
	if(isset($_SESSION["usuario"]["api_token"])){ $_GET["token"] = $_SESSION["usuario"]["api_token"]; }
	if(isset($_SESSION["usuario"]["id"])){ $userid = $_SESSION["usuario"]["id"]; }

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

	// Pesquisa grades
	$ret['rates'] = array();
	$opcoes = array();
	$sql = $mysqli->query("SELECT * FROM grades");
	while ($g = $sql->fetch_assoc()) {
		$ret['rates'][$g["grade_id"]]['id'] = $g["grade_id"];
		$ret['rates'][$g["grade_id"]]['name'] = utf8_encode($g["grade_nome"]);
		$ret['rates'][$g["grade_id"]]['min_odd'] = $g["grade_odd_minima"];
		$ret['rates'][$g["grade_id"]]['rules'] = array();
	}

	// Pesquisa regras
	$sql = $mysqli->query("SELECT * FROM opcoes_grade");
	while($o = $sql->fetch_assoc()){
		if(!isset($ret['rates'][$o["og_grade"]])){ continue; }

		$i = count($ret['rates'][$o["og_grade"]]["rules"]);
		$ret['rates'][$o["og_grade"]]["rules"][$i]["min"] = $o["og_minimo"];
		$ret['rates'][$o["og_grade"]]["rules"][$i]["max"] = $o["og_maximo"];
		$ret['rates'][$o["og_grade"]]["rules"][$i]["percent"] = $o["og_comissao"];
	}

	// Pega dados do usuario
	$ret['success'] = 'Pronto! Listado com sucesso.';
	$ret['status'] = 'success';
	finishJSONRequest($ret);
?>