<?php
/*	
	사용자의 친구 API
	
	TO DO LIST
	* 친구 요청 / 수락
	* 친구 리스트
	* 친구 검색(id로 검색)
	* 리스트 공유 
		전체공유 / 친구공유인 경우에만.. 
	
	DONE 
	 * 친구 추천(일단 랜덤) 
		추후 지역 / rank 등으로 suggestion 알고리즘 변경	
*/
class Friend{
	/*
		1. 나랑 현재 친구가 아닌 사람 
		2. 계정 공개 true인 사람 
	*/
	function suggest($a,$method = 'random'){
		if(!$a[limit])
			$limit = 10;
		else
			$limit = $a[limit];
		$people = query("
			SELECT info.* FROM info
			JOIN (SELECT CEIL(RAND() * (SELECT MAX(no) FROM info)) AS no) AS info2 
			WHERE 
				info.no >= info2.no 
				and info.privacy = 0 
				and info.isactive = 1
			ORDER BY info.no ASC LIMIT ".$limit
		);

		$friends = $this->get($a);
		foreach($people as $i => $p){
			unset($people[$i][profileimg]);
			if($friends[result] != 'fail'){
				foreach($friends as $f){
					if(array_search($f[username], $p) !== false){
						unset($people[$i]);
					}					
				}
			}
			if(array_search($a[username], $p) !== false){
				unset($people[$i]);
			}	
		}
		return array_values($people);	
	}
	
	function get($a){
		if(!$a[username]){
			return response(506);
		}	
		$info = new Info();
		$friends = query("
			select *
			from relationship
			where 
				(username_1=:username or username_2=:username)
			and status = 'accepted'
		", $a);	
		if(!empty($friends)){
			$myname = trim($a[username]);
			
			foreach($friends as $f){
				if($myname!=$f[username_1]){
					$a[username] = $f[username_1];
					if($info->get($a))
						$friendArr[] = $info->get($a);
				}	
				if($myname!=$f[username_2]){
					$a[username] = $f[username_2];
					if($info->get($a))
						$friendArr[] = $info->get($a);
				}	
			}		
			return $friendArr;
		}else{
			return response(204);
		}
	}
	
}
/*
	username_2: 요청받은사람
	username_1: 요청한사람
*/
class Relationship{
	function 받은요청가져오기($a){
		$people = query("
			select relationship.no, relationship.username_1 as stranger, info.main_profileimg , info.rank, info.bio,
			relationship.username_2 as username, relationship.status
			from relationship as relationship
			join info as info on relationship.username_1 = info.username
			where 
				relationship.username_2=:username
				and relationship.status = 'pending'
				and info.isactive=1
		", $a);
		return $people;
	}
	function 보낸요청리스트가져오기($a){
		$people = query("
			select relationship.no, relationship.username_1 as username, info.main_profileimg, info.rank, info.bio,
			relationship.username_2 as friendname, relationship.status
			from relationship as relationship
			join info as info on relationship.username_2 = info.username
			where 
				relationship.username_1=:username
				and relationship.status = 'pending'
				and info.isactive=1
		", $a);
		return $people;
	}
	function 친구여부확인($a){
		$result = query('select * from relationship where
		(username_1=:username and username_2=:stranger) or 
		(username_1=:stranger and username_2=:username) and status="accepted"', $a);
		
		if(empty($result))
			$isfriend[isfrined] = false;	
		else
			$isfriend[isfriend] = true;			
		return $isfriend;
	}
	function 관계확인($a){
		$result = query('select * from relationship where
		(username_1=:username and username_2=:stranger) or 
		(username_1=:stranger and username_2=:username)', $a);
		
		if(empty($result))
			$relation[status] ='unknown';	
		else{
			$status = $result[0][status];
			if($status == 'pending'){
				if ($result[0][action_username] == $a[username])
					$relation[status] = 'pending by stranger';
				else
					$relation[status] = 'pending by me'; 
			}else{
				$relation[status] = 'friend';
			}	
		}	
		return $relation;
	}	
}
/*
	친구여부확인
*/
$app->action('user/friend/check', function(){
	$a = $_REQUEST;
	$relationship = new Relationship();
	$result = $relationship->친구여부확인($a);
	reply_json($result);
});

/*
	친구상태확인 
*/
$app->action('user/relationship/status', function(){
	$a = $_REQUEST;
	$relationship = new Relationship();
	$result = $relationship->관계확인($a);
	reply_json($result);
});

/*
	친구 추천 시 자기자신, 친구 제외하고 추천 (max 10)
*/
$app->action('user/friend/suggest', function(){
	$a = $_REQUEST;
	$friend = new Friend();
	$people = $friend->suggest($a);
	reply_json($people);
});
/*
	검색 시 사용자자신, 친구 제외 하고 검색 
*/
$app->action('user/friend/search', function(){
	$a = $_REQUEST;
	$friend = new Friend();
	$friends = $friend->get($a);
	
	$keyword = $a[keyword];
	
	if($a[keyword]){
		$a[keyword] = "$a[keyword]%";
		if(strpos($a[keyword],'@')){
			$condition='email like :keyword';
		}else{
			$condition = 'username like :keyword';
		}
	}else{
		reply_json(response(506));
		return;
	}
	$people = query("select * from info where isactive=1 and ".$condition, $a);

	foreach($people as $i => $p){
		if($friends[result]!='fail'){
			foreach($friends as $f){
				if(array_search($f[username], $p) !== false){
					unset($people[$i]);
				}		
			}
		}
		if(array_search($a[username],$p)!== false){
			unset($people[$i]);
		}
	}

	reply_json(array_values($people));
});


$app->action('user/friend/delete', function(){
	$a = $_REQUEST;
	$friend = new Friend();
	$result = query("
		delete from relationship 
		where 
			(status = 'accepted') and 
			(username_1=:username and username_2=:friendname) or
			(username_1=:friendname and username_2=:username) 
		", $a);
	if($result[numAffected]==1){
		$r[result] = 'success';
	}else{
		$r = response(404);
	}	
	reply_json($r);
});

/*
	사용자의 친구 리스트 가져오기
*/
$app->action('user/friend/fetch', function(){
	$info = new Info();
	$a = $_REQUEST;
	$friend = new Friend();
	//$me = $info->get($a);
	//$me[friends] = $friend->get($a);
	reply_json($friend->get($a));
});
/*
	status 
	- pending [요청중]
	- accepted [승인]
	- declined [거절]
	- blocked [차단]
	
	1. user/friend/request 
	요청한사람: username (자기자신)
	요청받은사람: requestee 
	status: pending 
	
	2. user/friend/accept
	status: accepted
	친구신청 ok할 당사자: username 
	친구신청 ok할 대상: requester 
*/
$app->action('user/friend/request', function(){
	$a = $_REQUEST;
	$friend = new Friend();
	$result = query("
		insert relationship 
		set 
			username_1=:username,
			username_2=:friendname, 
			status='pending', 
			action_username=:username
		", $a);
	if($result[numAffected]==1){
		$relationship = new Relationship();
		$result = $relationship->보낸요청리스트가져오기($a);		
		reply_json($result);
	}
});

$app->action('user/friend/request/cancle', function(){
	/*
	$a = $_REQUEST;
	$info = new Info();
	$friend = new Friend();
	$result = query("
		update relationship 
		set 
			status='declined', 
			action_username=:username
		where 	
			(username_1=:friendname and username_2=:username) or
			(username_1=:username and username_2=:friendname)
			
		", $a);
	$me = $info->get($a);
	$me[friends] = $friend->get($a);	
	reply_json($me);
	*/
	$a = $_REQUEST;
	$friend = new Friend();
	$result = query("
		delete from relationship 
		where 
			(username_1=:username and
			username_2=:friendname) or
			(username_1=:friendname and
			username_2=:username)			
		", $a);
	if($result[numAffected]==1){
		$r[result] = 'success';		
	}else{
		$r = response(404);		
	}
	reply_json($r);
});

$app->action('user/friend/accept', function(){
	$a = $_REQUEST;
	$info = new Info();
	$friend = new Friend();
	$result = query("
		update relationship 
		set 
			status='accepted', 
			action_username=:username
		where 	
			(username_1=:friendname and username_2=:username) or
			(username_1=:username and username_2=:friendname)
			
		", $a);
	if($result[numAffected]==1){
		reply_json($friend->get($a));	
	}else{
		reply_json(response(404));		
	}		
});

$app->action('user/friend/deny', function(){
	$a = $_REQUEST;
	$friend = new Friend();
	$result = query("
		delete from relationship 
		where 
			(username_1=:username and
			username_2=:friendname) or
			(username_1=:friendname and
			username_2=:username)			
		", $a);
	/*
	$a = $_REQUEST;
	$info = new Info();
	$friend = new Friend();
	$result = query("
		update relationship 
		set 
			status='deny', 
			action_username=:username
		where 	
			(username_1=:friendname and username_2=:username) or
			(username_1=:username and username_2=:friendname)
			
		", $a);
	*/
	//$me = $info->get($a);
	//$me[friends] = $friend->get($a);	
	echo '[]';
});

/*
	내가 받은 요청 리스트 
*/
$app->action('user/friend/get_received_requests', function(){
	$a = $_REQUEST;
	$relationship = new Relationship();
	$result = $relationship->받은요청가져오기($a);
	reply_json($result);
});

$app->action('user/friend/get_sent_requests', function(){
	$a = $_REQUEST;
	$relationship = new Relationship();
	$result = $relationship->보낸요청리스트가져오기($a);
	reply_json($result);
});
?>