<?php
/*
	사용자의 기본 정보
	
*/
class Info{
	function default_info($a){
		$info[no] = $a[no];
		$info[username] = $a[username];
		$info[email] = $a[email];
		$info[pw] = $a[pw];
		$info[main_profileimg] = $a[main_profileimg];
		if(!empty($a[profileimgs])){
			foreach($a[profileimgs] as $img)
				$info[profileimgs][] = $img[imgurl];
		}else{
			$info[profileimgs] = [];
		}	
		$info[bio] = $a[bio];
		$info[rank] = $a[rank];
		$info[privacy] = $a[privacy];
		$info[devices] = $a[devices];
		$info[creationtime] = $a[creationtime];
		return $info;
	}
	
	function get($a){
		if($a[username])
			$condition = " and username=:username";
		if($a[no])
			$condition = " and no=:no";
		$info = query("select * from info where isactive=1".$condition , $a);
		if($info[0])
		{
			$info = $info[0];
			$a[no] = $info[no];
			$profileimgs = query("select no, imgurl from info_profileimg where user_no=:no", $a);
			$info[profileimgs] = $profileimgs;
			$devices = query("select name, serial_number, creationtime from device where user_no=:no", $a);
			$info[devices] = $devices;
			$info = $this->default_info($info);
			return $info;
		}
	}
	
	function logincheck($a){
		if(filter_var($a[id], FILTER_VALIDATE_EMAIL)){
			$a[email] = $a[id];
			$condition = 'and email=:email';
		}else{
			$a[username] = $a[id];
			$condition = 'and username=:username';
		}	
		if(!$a[email] && !$a[username]){
			$result = response(506);
			return $result;
		}
		if(!$a[pw]){
			$result = response(506);
			return $result;
		}		
		
		$rows = query('select * from info where 1 '.$condition.' and pw=:pw and isactive=1', $a);
		
		if(count($rows)>0){
			$result = $rows[0];
			if($result['isconfirm'] == 0)
				$result = response(401);	
			else
			{
				$result['status'] = 'OK';
				
				$get_ip_address = $this->get_client_ip();
				$user_no = query('select no from info where email=:email or username=:username',$a);

				$a[user_no]=$user_no[0][no];
				$a[ip]=$get_ip_address;

				$device_no = query('select no from device where user_no=:user_no', $a);
				
				if(empty($device_no))
					return $result;
				else
					$a[device_no] = $device_no[0][no];
				
				$r = query("insert into info_ip set user_no=:user_no, ip = :ip, device_no=:device_no, is_local_ip=0",$a);
			}
			return $result;
		}else{
			$result = response(403);		
		}
		return $result;
	}	
	function generate_random_string($length = 10) {
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$charactersLength = strlen($characters);
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, $charactersLength - 1)];
		}
		return $randomString;
	}	
	function make_temporary_pw(){
		return $this->generate_random_string(5);
	}
	// Function to get the client IP address
	function get_client_ip() {
		$ipaddress = '';
		if (getenv('HTTP_CLIENT_IP'))
			$ipaddress = getenv('HTTP_CLIENT_IP');
		else if(getenv('HTTP_X_FORWARDED_FOR'))
			$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
		else if(getenv('HTTP_X_FORWARDED'))
			$ipaddress = getenv('HTTP_X_FORWARDED');
		else if(getenv('HTTP_FORWARDED_FOR'))
			$ipaddress = getenv('HTTP_FORWARDED_FOR');
		else if(getenv('HTTP_FORWARDED'))
		   $ipaddress = getenv('HTTP_FORWARDED');
		else if(getenv('REMOTE_ADDR'))
			$ipaddress = getenv('REMOTE_ADDR');
		else
			$ipaddress = 'UNKNOWN';
		return $ipaddress;
	}
	
	function existcheck($a){
		if($a[username]){
			$a[username] = trim($a[username]);
			$result = query('select * from info where username=:username', $a);
		}
		if($a[email]){
			$a[email] = trim($a[email]);
			$result = query('select * from info where email=:email', $a);
		}
		if(empty($result))
			$response = response();
		else
			$response = response(507);
		return $response;		
	}
}
/*
	사용자 로그인 진위여부 확인 API
*/
$app->action('user/logincheck', function () use($auth){
	$info = new Info();
	$result=$info->logincheck($_REQUEST);
	if($result[status] == 'OK')
		$result['accesskey'] = $auth->getAccesskey($result)['accesskey'];
	reply_json($result);	
});

/*
	사용자, username 중복 체크 API 
*/
$app->action('user/existcheck', function () use($auth){
	$info = new Info();
	reply_json($info->existcheck($_REQUEST));
});

/*
	사용자 NEW / MODIFY / GET / DELETE API
*/
$app->action('user/new', function (){
	$info = new Info();
	$a = $_REQUEST;

	if(!$a[email] || !$a[username] || !$a[pw]){
		reply_json(response(506));
		return;
	}
	if(!filter_var($a[email], FILTER_VALIDATE_EMAIL)){
		reply_json(response(509));
		return;
	}	
	$checkresult = $info->existcheck($_REQUEST);
	if($checkresult[result] == 'success'){
		$a[hash] = md5( rand(0,1000) );
		//인증메일발송 (/mail/joinconfirm)
		
		$상황별메일보내기 = new 상황별메일보내기;
		$메일성공여부 = $상황별메일보내기->회원가입확인($a);

		if($메일성공여부[result] == 'success'){
			//info DB에 회원정보 추가
			$result = query('insert into info set username=:username, email=:email, pw=:pw, hash=:hash', $a);
			$a[no] = $result[lastInsertId];
			
			// 회원가입 시 1개의 기기 등록 가능 
			if($a[serial_number] && $a[device_name] && $a[modelname] && $a[mac]){
				$a[mac] = strtoupper($a[mac]);
				$device_regist_result = query('
				insert into device set 
				user_no=:no, 
				name=:device_name,
				serial_number=:serial_number
				modelname=:modelname,
				mac=:mac
				', $a);
			}	
			if($result[numAffected] == 1)
				reply_json($info->get($a));
		}
	}else{
		reply_json($checkresult);
	}
	
});

$app->action('user/updateproperty', function () use($auth){
	$info = new Info();
	$a=$_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){	
		if($a[username])
			$condition = " username=:username, ";
		if($a[email])
			$condition = $condition." email=:email, ";	
		if($a[pw])
			$condition = $condition." pw=:pw, ";
		if(isset($a[bio]))
			$condition = $condition." bio=:bio, ";
		if($a[privacy])
			$condition = $condition." privacy=:privacy, ";
		
		if($_FILES[main_profileimg]){
			$image = new Image();
			$result=$image->uploadFile("../../roseimg/profile/", $_FILES["main_profileimg"], "medium");
			if($result[success]==1){
				$a[main_profileimg] = 'http://roseimg.modtv.co.kr/profile/'.$result[unique_name];
			}
			$condition = $condition." main_profileimg=:main_profileimg, ";
		}
		if(isset($a[main_profileimg])){
			$condition = $condition." main_profileimg=:main_profileimg, ";	
		}
		$result = query("
			update info set ".$condition."
				updatetime=now()
			where no=:no", $a);		
		reply_json($info->get($a));			
	}else{
		reply_json($authorized);
	}	
});

$app->action('user/get', function () use($auth){
	$info = new Info();
	$a=$_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){	
		reply_json($info->get($_REQUEST));
	}else{
		reply_json($authorized);
	}	
});

$app->action('user/delete', function () use($auth){
	$info = new Info();
	$a=$_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){	
		$user_no = query('select no from info where username=:username', $a);
		if($user_no)
			$a[user_no] = $user_no[0][no];
		
		$result = query('update info set isactive=0 where username=:username', $a);
		query('delete from device where user_no=:user_no', $a);
		if($result[numAffected] == 1){
			$r[result] = 'success';
			$r[msg] = $a[username].' 회원님의 계정이 비활성화 되었습니다.';
		}else{
			$r = response(404);
		}
		reply_json($r);
	}else{
		reply_json($authorized);
	}	
});
/*
	사용자 프로필 이미지 upload / delete 
*/
$app->action('user/profileimg/upload', function () use($auth){
	$info = new Info();
	$a=$_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){	
		if($_FILES["imgurl"]){
			$image = new Image();
			$result=$image->uploadFile("../../roseimg/profile/", $_FILES["imgurl"], "medium");
			if($result[success]==1){
				$a[imgurl] = 'http://roseimg.modtv.co.kr/profile/'.$result[unique_name];
			}
			$result = query("insert into info_profileimg set user_no=:no , imgurl=:imgurl", $a);
			reply_json($info->get($a));
		}
	}else{
		reply_json($authorized);
	}	
});

$app->action('user/profileimg/delete', function () use($auth){
	$info = new Info();
	$a=$_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){
		$is_mainimg = query("select no from info where no=:no and profileimg=:imgurl", $a);
		if(empty($is_mainimg)){
			$result = query("delete from info_profileimg where imgurl=:imgurl and user_no=:no", $a);
			reply_json($info->get($a));
		}else{
			reply_json(response(403));
		}	
	}else{
		reply_json($authorized);
	}	
});

/*
	사용자 기기등록
*/
$app->action('user/device/register', function () use($auth){
	$info = new Info();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){	
		$user_no = query('select no from info where username=:username', $a);
		if($user_no)
			$a[user_no] = $user_no[0][no];
		$a[mac] = strtoupper($a[mac]);
		
		$assigned_with_me = query('select mac, user_no from device where mac=:mac and user_no=:user_no', $a);
		
		if(empty($assigned_with_me)){
			$assigned_with_other = query('select mac from device where mac=:mac', $a);
			if(empty($assigned_with_other)){
				$result = query('
				insert into device set 
					user_no=:user_no, 
					name=:name, 
					serial_number=:serial_number,
					modelname=:modelname,
					mac=:mac 
				', $a);
				$a[no] = $a[user_no];
				if($result[numAffected] == 1)
					reply_json($info->get($a));	
			}else{
				reply_json(response(511));				
			}
		}else{
			reply_json(response(510));
		}
	}else{
		reply_json($authorized);
	}	
});

/*
	사용자 기기등록
*/
$app->action('user/device/unregister', function () use($auth){
	$info = new Info();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){	
		$user_no = query('select no from info where username=:username', $a);
		if($user_no)
			$a[user_no] = $user_no[0][no];
		$result = query('delete from device where user_no=:user_no and serial_number=:serial_number', $a);
		$a[no] = $a[user_no];
		if($result[numAffected] == 1)
			reply_json($info->get($a));
		else
			reply_json(response(404));
	}else{
		reply_json($authorized);
	}	
});
/*
	기기에서 기기등록 해제
*/
$app->action('user/device/unregister_serial', function () use($auth){
	$info = new Info();
	$a = $_REQUEST;
	$re = query('delete from device where serial_number=:serial_number', $a);
	if($re[numAffected] == 1)
	{
		$result[result] = 'success';
		$result[msg] = 'success to unregist device';
		reply_json($result);
	}
	else
		reply_json(response(404));
});
/*
	사용자 기기 리스트 가져오기
*/
$app->action('user/device/fetch', function () use($auth){
	$info = new Info();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){	
		$user_no = query('select no from info where username=:username', $a);
		if($user_no)
			$a[no] = $user_no[0][no];
		$devices = query("select name, serial_number, modelname, mac, creationtime from device where user_no=:no", $a);
		reply_json($devices);
	}else{
		reply_json($authorized);
	}	
});

/*
	사용자 랭크 
	1. 친구 숫자 + 공유 플레이리스트 숫자 (1~5 등급) 
	2. 친구 숫자 + 공유플레이숫자 range 

*/
$app->action('user/rank', function () use($auth){
	$users = query('select username from info where isconfirm=1 and isactive=1');
	foreach($users as $user){
		$a[username] = $user[username];
		//친구 숫자 + 공유플레이숫자 가져오기 
		$score = query("
			select 
				(select count(*) as friends from relationship where (username_1=:username or username_2=:username) and status = 'accepted')
				+ 
				(select count(*) as shareplaylist from playlist where toshare in (1,2) and username=:username)
			as score	
		", $a);
		
		$sum = $score[0][score];
		// 등급 산정하기 
		switch(true){
		// 금 ( 1~10 )
		case ($sum>=10000):
			$a[rank] = 1;break;
		case ($sum>=9500 && $sum<10000):
			$a[rank] = 2;break;
		case ($sum>=9000 && $sum<9500):
			$a[rank] = 3;break;
		case ($sum>=8500 && $sum<9000):
			$a[rank] = 4;break;
		case ($sum>=8000 && $sum<8500):
			$a[rank] = 5;break;
		case ($sum>=7500 && $sum<8000):
			$a[rank] = 6;break;
		case ($sum>=7000 && $sum<7500):
			$a[rank] = 7;break;
		case ($sum>=6500 && $sum<7000):
			$a[rank] = 8;break;
		case ($sum>=6000 && $sum<6500):
			$a[rank] = 9;break;
		case ($sum>=5500 && $sum<6000):
			$a[rank] = 10;break;			
		// 은 ( 11~20 )
		case ($sum>=5000 && $sum<5500):
			$a[rank] = 11;break;
		case ($sum>=4500 && $sum<5000):
			$a[rank] = 12;break;
		case ($sum>=4000 && $sum<5500):
			$a[rank] = 13;break;
		case ($sum>=3500 && $sum<4000):
			$a[rank] = 14;break;
		case ($sum>=3000 && $sum<3500):
			$a[rank] = 15;break;
		case ($sum>=2500 && $sum<3000):
			$a[rank] = 16;break;
		case ($sum>=2000 && $sum<2500):
			$a[rank] = 17;break;
		case ($sum>=1500 && $sum<2000):
			$a[rank] = 18;break;
		case ($sum>=1000 && $sum<1500):
			$a[rank] = 19;break;
		case ($sum>=900 && $sum<1000):
			$a[rank] = 20;break;			
		// 동 ( 21~30 )	
		case ($sum>=800 && $sum<900):
			$a[rank] = 21;break;
		case ($sum>=750 && $sum<800):
			$a[rank] = 22;break;
		case ($sum>=700 && $sum<750):
			$a[rank] = 23;break;
		case ($sum>=650 && $sum<700):
			$a[rank] = 24;break;
		case ($sum>=500 && $sum<650):
			$a[rank] = 25;break;
		case ($sum>=400 && $sum<500):
			$a[rank] = 26;break;
		case ($sum>=300 && $sum<400):
			$a[rank] = 27;break;
		case ($sum>=200 && $sum<300):
			$a[rank] = 28;break;
		case ($sum>=100 && $sum<200):
			$a[rank] = 29;break;
		case ($sum>=0 && $sum<100):
			$a[rank] = 30;break;		
		default:
			$a[rank] = 30;
			break;
		}
		$updateResult = query('update info set rank=:rank where username=:username', $a);
	}
	$result[result] = 'success';
	$result[msg] = 'user rank update done';
	reply_json($result);
});

/*
	임시 비밀번호 메일로 전송
*/
$app->action('user/make_temp_pw', function () use($auth){
	$a = $_REQUEST;
	$user = query("select username from info where email=:email", $a);
	if($user[0]){
		$a[username] = $user[0][username];
		$info = new Info;
		$temp_pw = $info->make_temporary_pw(5);
		$a[temp_pw_sha1] = sha1($temp_pw);
		query("update info set pw=:temp_pw_sha1 where email=:email", $a);
		$a[temp_pw] = $temp_pw;
		$상황별메일보내기 = new 상황별메일보내기;
		$결과 = $상황별메일보내기->임시비밀번호발급($a);
		if($결과[result] == 'success')
			reply_json($결과);
	}
});

/*
	sn 로 아이디(username / email 돌려주기)
*/
$app->action('user/find_id', function () use($auth){
	$a = $_REQUEST;
	$id_info = query("
	select info.username, info.email from info
	INNER join device
	on 
		device.user_no = info.no
	where 
		device.serial_number =:serial_number", $a);
	if(!empty($id_info))	
		reply_json($id_info[0]);
	else
		reply_json(response(404));
});

/*
	외부 IP 저장
*/
$app->action('user/local_ip/add', function () use($auth){
	$info = new Info();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	
	if($authorized['status'] == 'OK'){	
		$device_no = query('select no from device where user_no=:user_no', $a);
		if($device_no)
			$a[device_no] = $device_no[0][no];
		$result = query("insert into info_ip set user_no=:user_no, ip = :ip, device_no=:device_no, is_local_ip=1",$a);
		$a[no] = $a[user_no];
		if($result[numAffected] == 1)
			reply_json($info->get($a));
	}else{
		reply_json($authorized);
	}	
});

/*
	외부 IP 가져오기
*/
$app->action('user/local_ip/get', function () use($auth){
	$info = new Info();
	$a=$_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){	
		$device_no = query('select no from device where user_no=:user_no', $a);
		$a[device_no]=$device_no[0][no];
		
		$ip = query('select * from info_ip where device_no=:device_no and is_local_ip=1',$a);
		reply_json($ip);
	}else{
		reply_json($authorized);
	}	
});

/*
	source IP 가져오기
*/
$app->action('user/source_ip/get', function () use($auth){
	$info = new Info();
	$a=$_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){	
		$device_no = query('select no from device where user_no=:user_no', $a);
		
		$a[device_no]=$device_no[0][no];
		$ip = query('select * from info_ip where device_no=:device_no and is_local_ip=0',$a);
		
		reply_json($ip);
	}else{
		reply_json($authorized);
	}	
});
?>