<?php

function session($name, $value = null)
{
	if ($value) {
		return $_SESSION[$name] = $value;
	}

	if (isset($_SESSION[$name])) {
		return $_SESSION[$name];
	}
}

function cookie($name, $value = null)
{
	if ($value == null) {
		if (isset($_COOKIE[$name])) {
			return $_COOKIE[$name];
		} else {
			return null;
		}
	} else {
		setcookie($name, $value, time() + (86400 * 30), "/");
	}
}

function login_control()
{
	global $db;

	if (session("login") == true) {
		return 1;
	} else {

		$oturumveri = cookie('oturum');
		if ($oturumveri != null) {

			$oturum_array = json_decode(base64_decode($oturumveri), true);

			$username = isset($oturum_array['username']) ? $oturum_array['username'] : '';
			$password = isset($oturum_array['password']) ? $oturum_array['password'] : '';

			$query = $db->prepare("SELECT * FROM users WHERE user_username = ?");
			$query->execute(array(
				$username
			));

			if ($query->rowCount()) {
				$user = $query->fetch(PDO::FETCH_ASSOC);
				if (password_verify($password, $user["user_password"])) {
					if ($user["user_status"] != 0) {

						session("login", true);
						session("user_id", $user["user_id"]);
						session("user_permissions", $user["user_perms"]);

						return 1;
					}
				}
			}
		}
		return 0;
	}
}
