<?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['redeemcode']) && !empty($_REQUEST['token']))
{
	$token = mysqli_real_escape_string($conn, $_REQUEST['token']);
	if ($token == $_SESSION['Token']){
		//if token match
		$redeemcode = mysqli_real_escape_string($conn, $_REQUEST['redeemcode']);
		$redeemcode = strtolower($redeemcode);
		
		$stmt = $conn->prepare("SELECT id, redeem_name, redeem_image, redeem_total, redeem_type, redeem_for_chances, redeem_for_points FROM $table_redeem WHERE redeem_code = ? AND game_type = ? AND expire_date > now()");
		$stmt->bind_param("ss", $redeemcode, $gameType);
		$stmt->execute();
		$stmt->store_result();
		$num_of_rows = $stmt->num_rows;
		$stmt -> bind_result($id, $redeem_name, $redeem_image, $redeem_total, $redeem_type, $redeem_for_chances, $redeem_for_points);
		
		$array = [];
		while ($stmt->fetch()) {
			$array[] = array(
				'id' => $id,
				'redeem_name' => $redeem_name,
				'redeem_image' => $redeem_image,
				'redeem_total' => $redeem_total,
				'redeem_type' => $redeem_type,
				'redeem_for_chances' => $redeem_for_chances,
				'redeem_for_points' => $redeem_for_points
			);
		}
    	$stmt->free_result();
		$stmt->close();
		
		//redeem code exist
		if($num_of_rows > 0){
			//redeem code total available
			if($array[0]['redeem_total'] > 0){
				//check redeem code type
				$proceedType = true;
				$proceedRedeem = true;
				
				if($array[0]['redeem_type'] == 0){
					$proceedType = false;
					$dateformat = '';
				}else if($array[0]['redeem_type'] == 1){
					$dateformat = '';
				}else if($array[0]['redeem_type'] == 2){
					$dateformat = 'AND DATE(date_created) = CURDATE()';
				}else if($array[0]['redeem_type'] == 3){
					$dateformat = 'AND YEARWEEK(date_created)= YEARWEEK(CURDATE())';
				}else if($array[0]['redeem_type'] == 4){
					$dateformat = 'AND Year(date_created)=Year(CURDATE()) AND Month(date_created)= Month(CURDATE())';
				}
				
				if($proceedType){
					$stmt = $conn->prepare("SELECT id FROM $table_redemption_code WHERE game_type = ? AND member_id = ? AND redeem_id = ? $dateformat");
					$stmt->bind_param("sss", $gameType, $_SESSION['Member_ID'], $array[0]['id']);
					$stmt->execute();
					$stmt->store_result();
					$num_of_redeem_rows = $stmt->num_rows;
					
					if($num_of_redeem_rows > 0){
						$proceedRedeem = false;
					}
					
					$stmt->free_result();
					$stmt->close();
				}
				
				if($proceedRedeem){
					//update redeem total
					$newRedeemTotal = (int)$array[0]['redeem_total']-1;
					$stmt = $conn->prepare("UPDATE $table_redeem SET redeem_total=? WHERE id=? AND game_type=?");
					$stmt -> bind_param("sss", $newRedeemTotal, $array[0]['id'], $gameType) &&
					$stmt -> execute();
					$stmt->close();
					
					//insert redeem record
					$stmt = $conn->prepare("INSERT INTO $table_redemption_code (game_type, member_id, redeem_id) VALUES(?, ?, ?)");
					$stmt -> bind_param("sss", $gameType, $_SESSION['Member_ID'], $array[0]['id']);
					$stmt -> execute();
					$stmt->close();
					
					//update user points and chances
					$check_member_points = checkExistPoints($_SESSION['Member_ID'], $gameType);
					if(count($check_member_points) > 0){
						$update_member_point = $check_member_points[0]['member_point'];
						$update_member_chance = $check_member_points[0]['member_chance'];
						$update_member_score = $check_member_points[0]['member_score'];
					}
					
					$newChances = (int)$array[0]['redeem_for_chances'];
					$newPoints = (int)$array[0]['redeem_for_points'];
					
					if($newChances > 0 || $newPoints > 0){
						$update_member_chance += $newChances;
						$update_member_point += $newPoints;

						if(updateMemberPoints($update_member_point, $update_member_chance, $update_member_score, $_SESSION['Member_ID'], $gameType)){
							$_SESSION['Token'] = getToken(30);
						}
					}
					
					$data = array("redeem_name","redeem_image");
					$data_length = count($data);
					$outputNum = 1;
					
					for($i = 0; $i < $outputNum; $i++)
					{
						$comma = ',';
						if($i == ($outputNum-1)){
							$comma = '';	
						}

						$table_val = '';
						for($c = 0; $c < $data_length; $c++){
							$commaInner = ',';
							if($c == ($data_length-1)){
								$commaInner = '';	
							}
							if($data[$c] == 'redeem_image' && $array[$i][$data[$c]] !=''){
								$table_val .= '"'.$data[$c].'":"'.$redeem_upload_path.$array[$i][$data[$c]].'"'.$commaInner;
							}else{
								$table_val .= '"'.$data[$c].'":"'.$array[$i][$data[$c]].'"'.$commaInner;
							}
						}
						$top_data .= '{ '.$table_val.' }'.$comma;
					}
					echo '{"status":true, "token":"'.$_SESSION['Token'].'", "member_point":'.$update_member_point.', "member_chance":'.$update_member_chance.', "member_score":'.$update_member_score.', "datas":['.$top_data.'], "message":"Redeem code successfully redeemed."}';	
				}else{
					echo '{"status":false, "message":"'.$lang['server-redeem-failed'].'"}';
				}
			}else{
				echo '{"status":false, "message":"'.$lang['server-redeem-no-items'].'"}';
			}
		}else{
			echo '{"status":false, "message":"'.$lang['server-redeem-invalid-code'].'"}';
		}
	}else{
		echo '{"status":false, "message":"'.$lang['server-error-undefined-token'].'"}';	
	}
}else{
	echo '{"status":false, "message":"'.$lang['server-error'].'"}';	
}

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