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

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


$data = array('reward_name','reward_points','redeem_status','date_created');
$data_length = count($data);

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

$stmt = $conn->prepare("SELECT id FROM $table_redemption WHERE game_type = '$gameType' AND member_id = ?");
$stmt->bind_param("s", $_SESSION['Member_ID']);
$stmt->execute();
$stmt->store_result();
$num_of_rows = $stmt->num_rows;
$stmt->free_result();
$stmt->close();

$member_id = $_SESSION['Member_ID'];
$stmt = $conn->prepare("SELECT reward_id, redeem_status, date_created FROM $table_redemption WHERE game_type = '$gameType' AND member_id = $member_id ORDER by date_created $order LIMIT $limit");
$stmt->execute();
$stmt->store_result();
$num_of_results = $stmt->num_rows;
$stmt -> bind_result($reward_id, $redeem_status, $date_created);
$array = [];
while ($stmt->fetch()) {
	$array[] = array(
		'reward_id' => $reward_id,
		'redeem_status' => $redeem_status,
		'date_created' => $date_created
	);
}
$stmt->free_result();
$stmt->close();

$top_data = '';
for($i = 0; $i < $num_of_results; $i++)
{
	$reward_id = $array[$i]['reward_id'];
	$stmt = $conn->prepare("SELECT reward_name, reward_points FROM $table_rewards WHERE id = $reward_id");
	$stmt->execute();
	$stmt->store_result();
	$stmt -> bind_result($reward_name, $reward_points);
	$users = [];
	while ($stmt->fetch()) {
		$users[] = array(
			'reward_name' => $reward_name,
			'reward_points' => $reward_points
		);
	}
	$stmt->free_result();
	$stmt->close();
	
	$comma = ',';
	if($i == ($num_of_results-1)){
		$comma = '';	
	}
	
	$table_val = '';
	for($c = 0; $c < $data_length; $c++){
		$value = '';
		$commaInner = ',';
		if($c == ($data_length-1)){
			$value = date("Y-m-d", strtotime($array[$i][$data[$c]]));
			$commaInner = '';	
		}else if($c == 0){
			$value = $users[0]['reward_name'];
		}else if($c == 1){
			$value = $users[0]['reward_points'];
		}else{
			$value = $array[$i][$data[$c]];
		}
		$table_val .= '"'.$data[$c].'":"'.$value.'"'.$commaInner;
	}
	$top_data .= '{ '.$table_val.' }'.$comma;
}

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

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