<?php

include_once("password.inc.php");

/**
 * Checks that the user is logged in. 
 * @return Returns the row of the logged in user
 */
function check_user() {
	global $pdo;
	
	if(!isset($_SESSION['userid']) && isset($_COOKIE['identifier']) && isset($_COOKIE['securitytoken'])) {
		$identifier = $_COOKIE['identifier'];
		$securitytoken = $_COOKIE['securitytoken'];
		
		$statement = $pdo->prepare("SELECT * FROM securitytokens WHERE identifier = :identifier");
		$result = $statement->execute(array('identifier' => $identifier));
		$securitytoken_row = $statement->fetch();
		//echo $securitytoken;

		if(sha1($securitytoken) !== $securitytoken_row['securitytoken']) {
			//Vermutlich wurde der Security Token gestohlen
			//Hier ggf. eine Warnung o.ä. anzeigen
			echo 'In der letzte Sitzung nicht abgemeldet oder neuer/anderen Browser genutzt.<br><br><br>';
		} else { //Token war korrekt
			//Setze neuen Token
			$neuer_securitytoken = random_string();
			$insert = $pdo->prepare("UPDATE securitytokens SET securitytoken = :securitytoken WHERE identifier = :identifier");
			$insert->execute(array('securitytoken' => sha1($neuer_securitytoken), 'identifier' => $identifier));
			setcookie("identifier",$identifier,time()+(3600*24*365)); //1 Jahr Gültigkeit
			setcookie("securitytoken",$neuer_securitytoken,time()+(3600*24*365)); //1 Jahr Gültigkeit
	
			//Logge den Benutzer ein
			$_SESSION['userid'] = $securitytoken_row['user_id'];
		}
	}
	
	
	if(!isset($_SESSION['userid'])) {
		die('Bitte zuerst <a href="login.php" >einloggen</a>');
	}
	

	$statement = $pdo->prepare("SELECT * FROM users WHERE id = :id");
	$result = $statement->execute(array('id' => $_SESSION['userid']));
	$user = $statement->fetch();
	return $user;
}

/**
 * Returns true when the user is checked in, else false
 */
function is_checked_in() {
	return isset($_SESSION['userid']);
}

function is_checked_in_index() {
	if( isset($_SESSION['userid']) || isset($_COOKIE['identifier'])){
		return true;
	}else{
		return false;
	}
}

/**
 * Returns a random string
 */
function random_string() {
	if(function_exists('openssl_random_pseudo_bytes')) {
		$bytes = openssl_random_pseudo_bytes(16);
		$str = bin2hex($bytes); 
	} else if(function_exists('mcrypt_create_iv')) {
		$bytes = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
		$str = bin2hex($bytes); 
	} else {
		//Replace your_secret_string with a string of your choice (>12 characters)
		$str = md5(uniqid('your_secret_string', true));
	}	
	return $str;
}

/**
 * Returns the URL to the site without the script name
 */
function getSiteURL() {
	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	return $protocol.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/';
}

/**
 * Outputs an error message and stops the further exectution of the script.
 */
function error($error_msg) {
	include("templates/header.inc.php");
	include("templates/error.inc.php");
	include("templates/footer.inc.php");
	exit();
}

/**
 * Prüft, ob der Benutzer administrator ist
 */
function check_admin() {
	global $pdo;
	
	if(isset($_SESSION['userid'])) {
		$statement = $pdo->prepare("SELECT userid FROM users_admin WHERE userid = :id");
		$statement->execute(array('id' => $_SESSION['userid']));
		$count = $statement->rowCount();
		
		if($count == 1){
			return true;
		}else{
			return false;
		}
	}else{
		return false;
	}


}

/**
 * Non-invasive admin check that prefers the `users.admin` flag but
 * falls back to the legacy `users_admin` table. Does not modify
 * `check_user()` behavior.
 */
function is_admin_user() {
	global $pdo;

	if (!isset($_SESSION['userid'])) {
		return false;
	}

	// Prefer the admin flag in users table (supports BIT(1) or TINYINT)
	$stmt = $pdo->prepare("SELECT admin FROM users WHERE id = ?");
	$stmt->execute([$_SESSION['userid']]);
	$row = $stmt->fetch();
	if ($row && !empty($row['admin'])) {
		return true;
	}

	// Fallback to legacy users_admin table
	$statement = $pdo->prepare("SELECT userid FROM users_admin WHERE userid = :id");
	$statement->execute(array('id' => $_SESSION['userid']));
	return ($statement->rowCount() == 1);
}
/**
 * Prüft, ob der Benutzer Bearbeiter ist
 */
function check_worker() {
	global $pdo;
	
	if(isset($_SESSION['userid'])) {
		$statement = $pdo->prepare("SELECT userid FROM users_worker WHERE userid = :id");
		$statement->execute(array('id' => $_SESSION['userid']));
		$count = $statement->rowCount();
		
		if($count == 1){
			return true;
		}else{
			return false;
		}
	}else{
		return false;
	}


}



function isValidSequence($sequence) {
    $events = explode(',', $sequence);
    $previousType = null;

    foreach ($events as $type) {
        if ($previousType === $type) {
            // Ein Fehler, wenn zwei gleiche Typen aufeinanderfolgen
            return false;
        }
        $previousType = $type;
    }

    // Überprüfen Sie, ob die Sequenz mit einem KOMMEN beginnt und einem GEHEN endet
    return $events[0] === 'KOMMEN' && end($events) === 'GEHEN';
}


?>