<?php
include 'dbconn.php';
include 'func.php';

if (!isset($_SESSION['LoggedIn'.$session_app])) {
	echo '{"status":false, "message":"'.$lang['session-timeout'].'", "session":false}';
	exit();
}

if(!empty($_REQUEST['limit']))
{
	$data = array('member_id','member_point','member_name');
	$data_length = count($data);

	$reverse = isset($_REQUEST['reverse']) == 1 ? $_REQUEST['reverse'] : '';
	$order = $reverse == 'true' ? 'ASC' : 'DESC';
	$limit = isset($_REQUEST['limit']) == 10 ? $_REQUEST['limit'] : '';
	$format = isset($_REQUEST['format']) == 10 ? $_REQUEST['format'] : '';

	$dateformat = '';
	if($format != ''){
		if($format == 'daily'){
			$dateformat = 'AND DATE(date_updated) = CURDATE()';
		}else if($format == 'weekly'){
			$dateformat = 'AND YEARWEEK(date_updated)= YEARWEEK(CURDATE())';
		}else if($format == 'monthly'){
			$dateformat = 'AND Year(date_updated)=Year(CURDATE()) AND Month(date_updated)= Month(CURDATE())';
		}
	}

	$stmt = $conn->prepare("SELECT member_id, member_point FROM $table_points WHERE game_type = '$gameType' $dateformat ORDER by member_point $order, date_updated ASC LIMIT $limit");
	$stmt->execute();
	$stmt->store_result();
	$num_of_rows = $stmt->num_rows;
	$stmt -> bind_result($member_id, $member_point);
	$users = [];
	while ($stmt->fetch()) {
		$users[] = array(
			'member_id' => $member_id,
			'member_point' => $member_point
		);
	}
	$stmt->free_result();
	$stmt->close();

	$top_data = '';

	for($i = 0; $i < $num_of_rows; $i++)
	{
		$member_id = $users[$i]['member_id'];
		$stmt = $conn->prepare("SELECT member_name FROM $table_member WHERE id = ?");
		$stmt->bind_param("s", $member_id);
		$stmt->execute();
		$stmt->store_result();
		$stmt -> bind_result($member_name);

		$names = [];
		while ($stmt->fetch()) {
			$names[] = array(
				'member_name' => $member_name
			);
		}
		$stmt->free_result();
		$stmt->close();

		$comma = ',';
		if($i == ($num_of_rows-1)){
			$comma = '';	
		}

		$table_val = '';
		for($c = 0; $c < $data_length; $c++){
			$value = '';
			$commaInner = ',';
			if($c == ($data_length-1)){
				$value = $names[0][$data[$c]];
				$commaInner = '';	
			}else{
				$value = $users[$i][$data[$c]];			
			}
			$table_val .= '"'.$data[$c].'":"'.$value.'"'.$commaInner;
		}
		$top_data .= '{ '.$table_val.' }'.$comma;
	}

	if($num_of_rows > 0){
		echo '{"status":true, "datas":['.$top_data.']}';
	}else{
		echo '{"status":false}';
	}
}else{
	echo '{"status":false}';
}

// Close connection
mysqli_close($conn);
?>