<?php
header("Content-Type: application/json");

$maestro_id = $_POST["MaestroID"];
$player_id = $_POST["PlayerID"];
$default_start_time = $_POST["DefaultStartTime"];
// echo $maestro_id." / ".$player_id;

include "./../lib/send_reply_json.php";
include "./../setup/connect_db.php";


$start_time = $default_start_time;
$left_time = null;
$saved_date_time = null;
$subject_name = "";


// get license_time data
$time_data = get_time_data($maestro_id, $player_id);
// set_data("timeData", $time_data);

// if license_time data is not exist
// then make new license_time data
if($time_data["StartTime"] == null) {
	insert_default_time_data($maestro_id, $player_id, $default_start_time);
	$start_time = $default_start_time;
} else {
	$start_time = $time_data["StartTime"];
	$left_time = $time_data["LeftTime"];
	$saved_date_time = $time_data["SavedDateTime"];
	$subject_name = $time_data["SubjectName"];
}

// send license_time data back to client
set_data("startTime", $start_time);
set_data("leftTime", $left_time);
set_data("savedDateTime", $saved_date_time);
set_data("subjectName", $subject_name);
send_result_success();
exit;



function get_time_data($maestro_id, $player_id) {
	global $db_conn;

	$query = "
		SELECT StartTime, LeftTime, SavedDateTime, SubjectName
		FROM license_time
		WHERE MaestroID = ? AND PlayerID = ?
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("ii", $maestro_id, $player_id);
	$stmt->execute();
	$stmt->bind_result($start_time, $left_time, $saved_date_time, $subject_name);
	$stmt->fetch();
	$stmt->close();

	$license_time["StartTime"] = $start_time;
	$license_time["LeftTime"] = $left_time;
	$license_time["SavedDateTime"] = $saved_date_time;
	$license_time["SubjectName"] = $subject_name;

	return $license_time;
}

function insert_default_time_data($maestro_id, $player_id, $default_start_time) {
	global $db_conn;

	$query = "
		INSERT INTO license_time (MaestroID, PlayerID, StartTime, SubjectName)
		VALUES (?, ?, ?, '');
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("iii", $maestro_id, $player_id, $default_start_time);
	$stmt->execute();
}

?>