<?php

	// 確率によりランダムランクを作成
	// 0:C ～ 4:SS
	function createRandomRank()
	{
		// 0～100までの乱数を生成
		$chance = rand(0, 100);
		
		// 5% 以下だったら、SSランク（4）のカードになる
		if ($chance < 5) 
			return 4; 
		
		// 15% 以下だったら、Sランク（3）のカードになる
		if ($chance < 15)
			return 3; 

		// 35% 以下だったら、Aランク（2）のカードになる
		if ($chance < 35)
			return 2; 

		// 65% 以下だったら、Bランク（1）のカードになる
		if ($chance < 65)
			return 1; 

		// 残りは C(0)
		return 0;
	}

	// ランクを用いて、ランダムのカードを返す
	// $dbh:  データベースを検索するためのPDO
	// $rank: カードのランク
	function getCardWithRank($dbh, $rank)
	{
		// SQL文を構築
		$sql = "SELECT * FROM cards WHERE rank = " . $rank;
		
		// すべてのレコードを取得
		$result = $dbh->query($sql);
		$records = $result->fetchAll(); 
		
		// ランダムのを選択
		$count = sizeof($records);
		$idx   = rand(0, $count-1);
		return $records[$idx];
	}

	// ユーザーにカードを追加する
	// $dbh:    データベースを検索するためのPDO
	// $userID: ユーザーID
	// $cardID: カードID
	function addCardToPlayer($dbh, $userID, $cardID)
	{
		// SQL文を構築
		$sql = "INSERT INTO user_cards (user_id, card_id, count) "
			 . "VALUES ($userID, $cardID, 1) "
			 . "ON DUPLICATE KEY UPDATE count = count + 1";
			 
		// 実行
		$result = $dbh->exec($sql);
	}
	
	// ガチャの数を減らす
	// $dbh:    データベースを検索するためのPDO
	// $userID: ユーザーID
	function decreaseGachaPullCount($dbh, $userID)
	{
		// SQL文を構築
		$sql = "UPDATE gacha SET count = count - 1 "
		     . "WHERE user_id = " . $userID;
			 
		// 実行
		$result = $dbh->exec($sql);
	}

	// JSONを返すべき
	header("Content-Type: application/json; charset=utf-8");

	// 接続 
	$dbh = new PDO('mysql:host=localhost; dbname=card_game', "root", "", [PDO::ATTR_PERSISTENT => true]);

	// ユーザーID
	$userID = $_POST['user_id'];

	$rank = createRandomRank();
	$card = getCardWithRank($dbh, $rank);
	addCardToPlayer($dbh, $userID, $card['id']);
	decreaseGachaPullCount($dbh, $userID);
	
	// カード情報を返す
	$json['card']['id']           = $card['id'];
	$json['card']['rank']         = $card['rank'];
	$json['card']['picture_id']   = $card['picture_id'];
	$json['card']['monster_name'] = $card['monster_name'];
	$json['card']['atk_value']    = $card['attack'];
	$json['card']['def_value']    = $card['defense'];
	$json['card']['hp_value']     = $card['hit_points'];	

	print(json_encode($json));
?>