<?php

require "../Admin/include/db.php";

define("L_ERROR", "Error");
define("L_OK", "Ok");

// ========
// DATABASE
// ========

function db_query($query) {
	global $conn;
	
	$result = mysqli_query($conn, $query);
	if (!$result) {
	  fatal("E001", mysqli_error($conn)); // will exit()
	}
	
	return $result;
}

function db_query_insert($query) {
	global $conn;
	
	$result = db_query($query);
	$id = $conn->insert_id;
	
	return $id;	
}

function db_query_get($query, $field, $must_exist = true) {
	global $conn;
	
	$result = db_query($query);
	
	if (mysqli_num_rows($result) <= 0) {
	  if ($must_exist) fatal("E004"); // will exit()
	  else return null;
	}
	
	$row = mysqli_fetch_assoc($result);
	
	return $row[$field];
}

function db_stmt_execute($stmt) {
	if (mysqli_stmt_execute($stmt)) return true;
	fatal("E001", mysqli_stmt_errno($stmt) . ": " . mysqli_stmt_error($stmt));	// will exit()
}

function db_stmt_execute_result($stmt) {
	if (mysqli_stmt_execute($stmt)) {
		return mysqli_stmt_get_result($stmt);
	}
	fatal("E001", mysqli_stmt_errno($stmt) . ": " . mysqli_stmt_error($stmt));	// will exit()
}

// ========
// RESPONSE
// ========

function response_json($result, $data, $text = "") {
	$response = array( "result" => $result, "data" => $data, "text" => $text);
	echo json_encode($response);  
	exit();
}

function response_json_ok($data, $text = "") {
	response_json(L_OK, $data, $text);
}

function response_json_error($severity, $error_code, $msg = "", $text = "") {
	response_json(L_ERROR, error_data($severity, $error_code, $msg), $text);
}

// =============
// RESULT ERRORS
// =============

// E001: Database error.
// E002: Username not found.
// E003: Password mismatch.
// E004: General SQL error (id mismatch?).
// E005: Invalid session.
// E006: Invalid post data.
// E007: User is not active, cannot log in.

function error_data($severity, $error_code, $msg = "") {
  return array( "severity" => $severity, "error_code" => $error_code, "msg" => $msg );
}

function error_json($severity, $error_code, $msg = "") {
  $errordata = error_data($severity, $error_code, $msg);
  return json_encode($errordata);
}

function fatal($error_code, $msg = "") {
	response_json_error(L_ERROR, $error_code, $msg); // will exit()
}

// ==============
// PLAYER ACTIONS
// ==============

// A001: User logged in
// A002: User state updated

function player_action($session_id, $chapter_name, $variant_name, $screen_name, $action_type, $action_info) 
{	
	global $conn;

	$sql = "insert into hynek_actions(session_id, chapter_name, screen_name, variant_name, action_type, action_info) values(?, ?, ?, ?, ?, ?)";
	
	$stmt = mysqli_prepare($conn, $sql);
		
	mysqli_stmt_bind_param($stmt, "isssss", $session_id, $chapter_name, $screen_name, $variant_name, $action_type, $action_info);
	
	db_stmt_execute($stmt);
	
	$actionid = $conn->insert_id;
			
	$actiontime = db_query_get("select action_time from hynek_actions where id = " . $actionid, "action_time");	
	
	$sql = "update hynek_sessions set last_action_id = " . $actionid . ", last_action_time = '" . $actiontime . "' where id = '" . $session_id . "'";
	
	db_query($sql);	
}

// ============
// PLAYER STATE
// ============

function player_set_state($user_id, $key, $value) {
	return player_set_state_json($user_id, $key, json_encode($value));
}

function player_set_state_json($user_id, $key, $value_json) {
	
	global $conn;
	
	// GET SESSION SAFE
	
	$sql = "select * from hynek_state where (user_id = ?) and (state_name = ?)";
	$stmt = mysqli_prepare($conn, $sql);

	mysqli_stmt_bind_param($stmt, "is", $user_id, $key);

	$result = db_stmt_execute_result($stmt);

	if (mysqli_num_rows($result) <= 0) {
		// STATE DOES NOT EXIST YET
		// => create new one
		
		$sql = "insert into hynek_state(user_id, state_name, state_json) value (?, ?, ?)";
		$stmt = mysqli_prepare($conn, $sql);
		
		mysqli_stmt_bind_param($stmt, "iss", $user_id, $key, $value_json);
		
		db_stmt_execute($stmt);
	} else {
		// STATE ALREADY EXIST
		// => update it
		
		$sql = "update hynek_state set state_json = ? where (user_id = ?) and (state_name = ?)";
		$stmt = mysqli_prepare($conn, $sql);
		
		mysqli_stmt_bind_param($stmt, "sis", $value_json, $user_id, $key);
		
		db_stmt_execute($stmt);		
	}
	
	return $key . " => " . $value_json;
}

// ==========
// EXPORT CSV
// ==========

function export_all() {	
	return export_actions("hynek_actions_all", "select hynek_sessions.user_id, hynek_users.username, hynek_actions.* FROM (hynek_actions inner join hynek_sessions on hynek_actions.session_id = hynek_sessions.id) INNER JOIN hynek_users ON (hynek_sessions.user_id = hynek_users.id) order by id desc");
}

function export_user($user_id) {
	return export_actions("hynek_actions_user_" . $user_id, "select hynek_sessions.user_id, hynek_users.username, hynek_actions.* FROM (hynek_actions inner join hynek_sessions on hynek_actions.session_id = hynek_sessions.id AND hynek_sessions.user_id = " . $user_id . ") INNER JOIN hynek_users ON (hynek_sessions.user_id = hynek_users.id) order by id desc");
}

function export_session($session_id) {
	return export_actions("hynek_actions_session_" . $session_id, "select hynek_sessions.user_id, hynek_users.username, hynek_actions.* FROM (hynek_actions inner join hynek_sessions on hynek_actions.session_id = hynek_sessions.id AND hynek_sessions.id = " . $session_id . ") INNER JOIN hynek_users ON (hynek_sessions.user_id = hynek_users.id) order by id desc");
}

function export_actions($filename_prefix, $query) {
	
	$date = date('Y-m-d_h-m-s', time());
	$filename = $filename_prefix . "_" . $date . ".csv";
	
	$result = db_query($query);
	
	$file = fopen($filename, "w");
	
	$line = "user_id;user_name;session_id;action_id;action_time;chapter;variant;screen;type;info;note";
	fwrite($file, $line . "\r\l");
	
	while ($row = mysqli_fetch_assoc($result)) {
		$line = "";
		$line = $line . $row["user_id"];
		$line = $line . ";" . $row["username"];
		$line = $line . ";" . $row["session_id"];
		$line = $line . ";" . $row["id"];		
		$line = $line . ";" . $row["action_time"];
		$line = $line . ";" . $row["chapter_name"];
		$line = $line . ";" . $row["variant_name"];
		$line = $line . ";" . $row["screen_name"];
		$line = $line . ";" . $row["action_type"];
		$line = $line . ";" . $row["action_info"];
		$line = $line . ";" . $row["user_note"];		
		fwrite($file, $line . "\r\l");
	}
		
	fclose($file);
	
	return $filename;
}

// =========
// UTILITIES
// =========

function get_get($field, $must_exist = true, $default_value = null) {
	if (!isset($_GET[$field])) {
		if ($must_exist) fatal("E006"); // will exit()
		return $default_value;
	}
	return $_GET[$field];
}

function get_post($field, $must_exist = true, $default_value = null) {
	if (!isset($_POST[$field])) {
		if ($must_exist) fatal("E006"); // will exit()
		return $default_value;
	}
	return $_POST[$field];
}

function check_session_post() {
	$session = get_post("session");
	return check_session($session);
}

// RETURNS hynek_sessions.id
function check_session($session) {
	global $conn;
	
	// GET SESSION SAFE
	
	$sql = "select * from hynek_sessions where session_id = ?";
	$stmt = mysqli_prepare($conn, $sql);

	mysqli_stmt_bind_param($stmt, "s", $session);

	$result = db_stmt_execute_result($stmt);

	if (mysqli_num_rows($result) <= 0) {
	  fatal("E005"); // will exit()
	}

	$row = mysqli_fetch_assoc($result);

	// CHECK ACTIVE

	if ($row["active"] <= 0) {
		fatal("E005", "Session not active anymore."); // will exit()
	}
	
	return $row["id"];
}

function get_session_user($session_id) 
{
	global $conn;
	
	// GET SESSION SAFE
	
	$sql = "select * from hynek_sessions where id = ?";
	$stmt = mysqli_prepare($conn, $sql);

	mysqli_stmt_bind_param($stmt, "s", $session_id);

	$result = db_stmt_execute_result($stmt);

	if (mysqli_num_rows($result) <= 0) {
	  fatal("E005"); // will exit()
	}

	$row = mysqli_fetch_assoc($result);

	// CHECK ACTIVE

	if ($row["active"] <= 0) {
		fatal("E005", "Session not active anymore."); // will exit()
	}
	
	return $row["user_id"];
}

