<?php

class system_user {
	
	public $my_data;
	public $users_data;
	
	public function __construct ($_uid) {
		$this->my_data = $this->get_user_data($_uid);
		$this->users_data[$_uid] = $this->my_data;
	}
	
	public function users_data($uid) {
		
		if(!isset($this->users_data[$uid])) {
			$this->users_data[$uid] = $this->get_user_data($uid);
		}
		
		return $this->users_data[$uid];
	}
	
	public function get_user_data($uid) {
		
		if(isset($this->users_data[$uid])) {
			return $this->users_data[$uid];
		}
		
		$query = "SELECT * FROM accounts WHERE id=".$uid;
		
		$result = run_query($query);
		
		if($result) {
			$returndata = array();
			
			if($row = $result->fetch_assoc()) {
				unset($row['password']);
				$returndata = $row;
			}
		} else {
			return false;
		}
		
		$this->users_data[$uid] = $returndata;
		
		return $returndata;
	}

	public function get_all_users() {
		// Select all but password
		$query = "SELECT id, login_name, user_name, email, disabled, admin, last_login FROM accounts";
		
		$result = run_query($query);
		
		if($result) {
			$returndata = array();
			
			while($row = $result->fetch_assoc()) {
				unset($row['password']);
				$returndata[$row['id']] = $row;
			}
		} else {
			return false;
		}
		
		$this->users_data = $returndata;
		
		return $returndata;
	}

	public function get_user_permissions($uid) : array {
		// Query from user_permission table all permissions for this users
		$query = "SELECT * FROM user_permission WHERE id=".$uid;

		$result = run_query($query);

		if($result) {
			$returndata = array();

			while($row = $result->fetch_assoc()) {
				$returndata[$row['function']] = $row['permission_lvl'];
			}

			return $returndata;
		} else {
			return [];
		}
	}

}

function update_last_login($user_id) {
	$returndata = false;
	
	$query = "UPDATE accounts SET last_login='".date("Y-m-d H:i:s", time())."' WHERE id=".$user_id;
	
	$returndata = run_query($query);
	
	return $returndata;
}

function save_user_data($variables) {
	/*
		$variables['id']
		$variables['user_name']
		$variables['email']
		$variables['password']
		$variables['password_confirm']
		$variables['disabled']
		$variables['admin']
	*/
	$returndata = false;

	// If password is set, check if it matches password_confirm
	if($variables['password'] && $variables['password'] != $variables['password_confirm']) {
		$GLOBALS['errors'][] = 'Passwords do not match';
		return false;
	}

	// Force admin to be 0 if not system admin
	if(!is_system_admin() && $variables['admin']) {
		$variables['admin'] = 0;
	}
	
	
	
	if($variables['id']) {
		// Update user dynamically

		$query = 'UPDATE accounts SET ';
		$query_set_values = '';


		if($variables['user_name']) {
			$query_set_values .= ', user_name="'.$variables['user_name'].'"';
		}

		if($variables['email']) {
			$query_set_values .= ', email="'.$variables['email'].'"';
		}

		if($variables['password']) {
			$query_set_values .= ', password="'.password_hash($variables['password'], PASSWORD_DEFAULT).'"';
		}

		if(isset($variables['disabled'])) {
			$query_set_values .= ', disabled='.$variables['disabled'];
		}

		if(isset($variables['admin'])) {
			$query_set_values .= ', admin='.$variables['admin'];
		}

		$query .= substr($query_set_values, 2);

		$query .= ' WHERE id='.$variables['id'];

		if(!$result = run_query($query)) {
			$GLOBALS['errors'][] = 'Error: Could not save user data';
			return false;
		}

		return true;
		
	} else {
		// user login_name, user_name and password must be set
		if(!$variables['login_name'] || !$variables['user_name'] || !$variables['password']) {
			$GLOBALS['errors'][] = 'Login name, user name and password must be set';
			return false;
		}

		// Insert new user with all values
		$query = 'INSERT INTO accounts (id, login_name, user_name, email, password, disabled, admin) VALUES ('.$variables['id'].', "'.$variables['login_name'].'", "'.$variables['user_name'].'", "'.$variables['email'].'", "'.password_hash($variables['password'], PASSWORD_DEFAULT).'", '.$variables['disabled'].', '.$variables['admin'].')';
		if(!$result = run_query($query)) {
			$GLOBALS['errors'][] = 'Error: Could not save user data';
			return false;
	
		}
	
		// Get last insert id
		$new_user_id = $variables['id'] ? $variables['id'] : get_insert_id();
	
		// Set permission for fyrk_projekt to 100
		$query = "INSERT INTO user_permission (id, function, permission_lvl) VALUES (".$new_user_id.", 'fyrk_project', 100) ON DUPLICATE KEY UPDATE permission_lvl=VALUES(permission_lvl)";

		if(!$result = run_query($query)) {
			$GLOBALS['errors'][] = 'Error: Could not save fykr permission';
			return false;
		}
	
		return true;
	
	}

}

function update_user_permission($variables) {
	/*
		$variables['user_id']
		$variables['function_id']
		$variables['permission_lvl']
	*/

	// Insert and update on duplicate key
	$query = "INSERT INTO user_permission (id, function, permission_lvl) VALUES (".$variables['user_id'].", '".$variables['function_id']."', ".$variables['permission_lvl'].") ON DUPLICATE KEY UPDATE permission_lvl=VALUES(permission_lvl)";

	if(!run_query($query)) {
		$GLOBALS['errors'][] = 'Error: Could not update user permission';
		return false;
	}

	return true;
}

function is_system_admin() {
	// Use session user_id to check if user is system admin
	$uid = $_SESSION['id'];

	$query = "SELECT admin FROM accounts WHERE id=".$uid;

	$result = run_query($query);

	if($result) {
		if($row = $result->fetch_assoc()) {
			return $row['admin'];
		}
	}

	return false;
}