<?php
// セッションクッキーに httponly 属性を設定
ini_set('session.cookie_httponly', 1);
// セッションクッキーに secure 属性を設定
ini_set('session.cookie_secure', 1);

session_start();

// XSS攻撃を検知し、検知したら実行させない
header("X-XSS-Protection: 1; mode=block");
// クリックジャッキング対策
header('X-FRAME-OPTIONS: DENY');

require_once './include/include.php';

$title = "指輪着用感の記録";
$page = "入力の確認";

$date = new DateTime();
$date = $date->format("YmdHis");

$report_id = filter_input(INPUT_POST,"report_id");
$save_flag = filter_input(INPUT_POST,"save_flag");

try {
	$pdo = DBopen();

	if($save_flag === "Y"){
		// 記録した
		$select_sql = "SELECT * FROM report WHERE report_id = ?";
		$select = $pdo->prepare($select_sql);
		$select->bindValue(1,$report_id,PDO::PARAM_STR);
		$select->execute();
		if($row = $select->fetch()){
			$created = $row["created"];
			$created_date = $row["created_date"];
			$created_time = $row["created_time"];
		} else {
			throw new RuntimeException("対象が存在しない | report_id -> {$report_id}");
		}

		$check_date = new DateTime($created);
		$check_time = $check_date->format("H:i:s");
		if("04:00:00" <= $check_time && $check_time < "11:00:00"){
			// 朝
			$script = "item1_accessory();";
			$time_zone = 1;
		} else if("11:00:00" <= $check_time && $check_time < "17:00:00"){
			// 昼
			$script = "item2_accessory();";
			$time_zone = 2;
		} else {
			// 夜
			$script = "item3_accessory();";
			$time_zone = 3;
		}
		$datetime = $check_date->format("Y年n月j日 G:i:s");
		$report_finish_text = "記録を保存しました。<br>記録日時:{$datetime}";

		// 同日の同時間帯がすでに存在するのであればスクリプトを起動しない
		// 夜の場合、0時以降は前日として扱う必要がある？
		$count_sql = "SELECT COUNT(report_id) FROM report WHERE user_id = ? AND created_date = ? AND deleted != 1";
		switch($time_zone){
			case 1:
			$count_sql .= " AND created_time >= '04:00:00' AND created_time < '11:00:00'";
			break;
			case 2:
			$count_sql .= " AND created_time >= '11:00:00' AND created_time < '17:00:00'";
			break;
			case 3:
			// 夜の場合は記録した時間帯によっても分岐する？
			$count_sql .= " AND ((created_date = ? AND created_time < '04:00:00') OR (created_date = ? AND created_time >= '17:00:00'))";
			break;
		}

		$count = $pdo->prepare($count_sql);
		$count->bindValue(1,$_SESSION["user"],PDO::PARAM_STR);
		$count->bindValue(2,$created_date,PDO::PARAM_STR);
		if($time_zone === 3){
			if($check_time < "04:00:00"){
				// 日付が変わってからの記録
				$prev_date = new DateTime($created_date);
				$prev_date = $prev_date->modify("-1 days")->format("Y-m-d");
				$count->bindValue(3,$created_date,PDO::PARAM_STR);
				$count->bindValue(4,$prev_date,PDO::PARAM_STR);
			} else {
				// 当日の記録
				$next_date = new DateTime($created_date);
				$next_date = $next_date->modify("+1 days")->format("Y-m-d");
				$count->bindValue(3,$next_date,PDO::PARAM_STR);
				$count->bindValue(4,$created_date,PDO::PARAM_STR);
			}
		}
		$count->execute();
		$count_result = $count->fetchColumn();
		if($count_result > 1){
			// 2つ以上ある
			$script = "";
		}
	} else {
		// 記録していない
		$time_zone = "";
		$script = "";
		$report_finish_text = "記録は保存されませんでした。";
	}

	// 今までにどれだけ記録があるかを調べる
	$count_asa_sql = "SELECT COUNT(DISTINCT created_date) FROM report WHERE user_id = ? AND created_time >= '04:00:00' AND created_time < '11:00:00' AND deleted != 1";
	$count_asa = $pdo->prepare($count_asa_sql);
	$count_asa->bindValue(1,$_SESSION["user"],PDO::PARAM_STR);
	$count_asa->execute();
	$count_asa_result = $count_asa->fetchcolumn();

	$count_hiru_sql = "SELECT COUNT(DISTINCT created_date) FROM report WHERE user_id = ? AND created_time >= '11:00:00' AND created_time < '17:00:00' AND deleted != 1";
	$count_hiru = $pdo->prepare($count_hiru_sql);
	$count_hiru->bindValue(1,$_SESSION["user"],PDO::PARAM_STR);
	$count_hiru->execute();
	$count_hiru_result = $count_hiru->fetchcolumn();

	// 夜の記録の場合は0～4時の記録を前日にするために調整する
	$count_yoru_sql = "SELECT COUNT(DISTINCT CAST((created - INTERVAL 4 HOUR) AS DATE)) FROM report WHERE user_id = ? AND (created_time < '04:00:00' OR created_time >= '17:00:00') AND deleted != 1";
	$count_yoru = $pdo->prepare($count_yoru_sql);
	$count_yoru->bindValue(1,$_SESSION["user"],PDO::PARAM_STR);
	$count_yoru->execute();
	$count_yoru_result = $count_yoru->fetchcolumn();

	if($time_zone === 1 && $script !== ""){
		// 朝の記録でスクリプトを起動する
		$count_asa_result--;
	}

	if($time_zone === 2 && $script !== ""){
		// 朝の記録でスクリプトを起動する
		$count_hiru_result--;
	}

	if($time_zone === 3 && $script !== ""){
		// 朝の記録でスクリプトを起動する
		$count_yoru_result--;
	}

} catch (Exception $e) {
	$error = $e->getMessage();
	$log = "error -> {$error}";
	Writelog($log,basename(__FILE__));
	require_once './error.php';
	exit;
}

if($count_asa_result >= 5 && $count_hiru_result >= 5 && $count_yoru_result >= 5){
	// すでに推奨回数を超えている
	$stamp_rally_text = stamp_rally_finished_text;
	$finish_img = "./stamps/finish.png";
	$frame_img = "./stamps/frame.png";

	// スクリプトを起動しない
	$script = "";
} else {
	// 推奨回数を終えていない
	$stamp_rally_text = stamp_rally_text;
	$finish_img = "";
	$frame_img = "";
}

?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1">
<link rel="icon" href="./img/favicon.ico">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="./js/script.js"></script>
<link href="./css/style.css" rel="stylesheet" type="text/css">
<title><?=$title?></title>
<script>
var item1_count = <?=$count_asa_result?>;
var item2_count = <?=$count_hiru_result?>;
var item3_count = <?=$count_yoru_result?>;

function main_img(){
	/*
	if(item1_count == 0 && item2_count == 0 && item3_count == 0){
		let img_elm = document.getElementById("main_img");
		if(img_elm){
			img_elm.src = "./stamps/main.png";
			img_elm.classList.add("stamp_motion");
		}
	}
	*/
}

function item1_accessory(){
	main_img();

	if(item1_count < 0){
		item1_count = 0;
	}
	if(item1_count > 4){
		item1_count = 4;
	}
	let img_elm = document.getElementById("accessories_img_1_"+item1_count);
	if(img_elm){
		let img_src = "item1_" + (item1_count + 1);
		img_elm.src = "./stamps/" + img_src + ".png";
		img_elm.classList.add("stamp_motion");
		item1_count++;
	}

	finish_img();
	count_img(1);
}

function item2_accessory(){
	main_img();

	if(item2_count < 0){
		item2_count = 0;
	}
	if(item2_count > 4){
		item2_count = 4;
	}
	let img_elm = document.getElementById("accessories_img_2_"+item2_count);
	if(img_elm){
		let img_src = "item2_" + (item2_count + 1);
		img_elm.src = "./stamps/" + img_src + ".png";
		img_elm.classList.add("stamp_motion");
		item2_count++;
	}

	finish_img();
	count_img(2);
}

function item3_accessory(){
	main_img();

	if(item3_count < 0){
		item3_count = 0;
	}
	if(item3_count > 4){
		item3_count = 4;
	}
	let img_elm = document.getElementById("accessories_img_3_"+item3_count);
	if(img_elm){
		let img_src = "item3_" + (item3_count + 1);
		img_elm.src = "./stamps/" + img_src + ".png";
		img_elm.classList.add("stamp_motion");
		item3_count++;
	}

	finish_img();
	count_img(3);
}

function finish_img(){
	if(item1_count >= 5 && item2_count >= 5 && item3_count >= 5){
		// 両方終わっている
		let frame_elm = document.getElementById("frame_img");
		if(frame_elm){
			let frame_src = "frame.png";
			frame_elm.src = "./stamps/" + frame_src;
			frame_elm.classList.add("finish_motion");
			frame_elm.addEventListener('animationend', () => {
				// アニメーション終了後にリセットアニメーションを流す
				reset_animation();
			});
			frame_elm.addEventListener('webkitAnimationEnd', () => {
				// アニメーション終了後にリセットアニメーションを流す
				reset_animation();
			});
		}

		let img_elm = document.getElementById("finish_img");
		let img_src = "finish.png";
		if(img_elm){
			img_elm.src = "./stamps/" + img_src;
			img_elm.classList.add("finish_motion2");
			img_elm.addEventListener('animationend', () => {
				// アニメーション終了後にリセットアニメーションを流す
				reset_animation();
			});
			img_elm.addEventListener('webkitAnimationEnd', () => {
				// アニメーション終了後にリセットアニメーションを流す
				reset_animation();
			});
		}
	}
}

function count_img(e){
	let elm;
	let value;
	let text;
	if(item1_count >= 5 && item2_count >= 5 && item3_count >= 5){
		elm = document.getElementById("count_box");
		text = "<?=stamp_rally_finished_text?>";
	} else {
		elm = document.getElementById("count"+e);
		switch(e){
			case 1:
			value = 5 - item1_count;
			break;
			case 2:
			value = 5 - item2_count;
			break;
			case 3:
			value = 5 - item3_count;
			break;
		}
		if(value <= 0){
			text = "CREARED";
		} else {
			text = "残り" + value + "回";
		}
	}
	elm.textContent = text;

	let animation_elm = document.querySelector(".stamp_motion");
	if(animation_elm){
		animation_elm.addEventListener('animationend', () => {
			// アニメーション終了後にリセットアニメーションを流す
			reset_animation();
		});
		animation_elm.addEventListener('webkitAnimationEnd', () => {
			// アニメーション終了後にリセットアニメーションを流す
			reset_animation();
		});
	}
}
function reset_animation(){
	document.getElementById("main_img").classList.add("reset_motion");
}

window.onload = function(){
	count_img(1);
	count_img(2);
	count_img(3);
	<?=$script?>
}

</script>
<style>
body,html {
	/*overflow: hidden;*/
}
</style>
</head>
<body>
	<?php
	require_once './header.php';
	?>
	<div id="main">
		<div id="report_finish_box">
			<?=$report_finish_text?>
		</div>
		<div id="stamp_box">
			<img src="./stamps/base.png" id="base_img">
			<img src="./stamps/main.png" id="main_img">
			<?php
			for($i=0;$i<5;$i++){
				$count = $i + 1;
				/*
				echo "<img src=\"./stamps/item1_{$count}.png\" id=\"accessories_img_1_{$i}\" class=\"accessory_img\">";
				echo "<img src=\"./stamps/item2_{$count}.png\" id=\"accessories_img_2_{$i}\" class=\"accessory_img\">";
				echo "<img src=\"./stamps/item3_{$count}.png\" id=\"accessories_img_3_{$i}\" class=\"accessory_img\">";
				*/
				if($count <= $count_asa_result){
					// すでに表示済みの画像
					$src1 = "./stamps/item1_{$count}.png";
				} else {
					$src1 = "";
				}
				if($count <= $count_hiru_result){
					// すでに表示済みの画像
					$src2 = "./stamps/item2_{$count}.png";
				} else {
					$src2 = "";
				}
				if($count <= $count_yoru_result){
					// すでに表示済みの画像
					$src3 = "./stamps/item3_{$count}.png";
				} else {
					$src3 = "";
				}
				echo "<img src=\"{$src1}\" id=\"accessories_img_1_{$i}\" class=\"accessory_img\">";
				echo "<img src=\"{$src2}\" id=\"accessories_img_2_{$i}\" class=\"accessory_img\">";
				echo "<img src=\"{$src3}\" id=\"accessories_img_3_{$i}\" class=\"accessory_img\">";
			}
			?>
			<img src="<?=$finish_img?>" id="finish_img">
			<img src="<?=$frame_img?>" id="frame_img">
		</div>
		<div id="count_box" class="small_text">
			<p><?=stamp_rally_text?></p>
			推奨記録回数は
			<br>
			<span class="indent">朝<span id="count1" class="indent"></span></span>
			<br>
			<span class="indent">昼<span id="count2" class="indent"></span></span>
			<br>
			<span class="indent">夜<span id="count3" class="indent"></span></span>
			<br>
			です。
		</div>
	</div>
	<div id="footer">
		<div id="footer_button_next" onclick="window.location.href='./top.php'">TOPに戻る</div>
	</div>
</body>
</html>
