<?php

//use Nette;
use Nette\Security\SimpleIdentity;

class AccountAuthenticator implements Nette\Security\Authenticator
{
	private $database;
	private $passwords;

	public function __construct(
		Nette\Database\Explorer $database,
		Nette\Security\Passwords $passwords
	) {
		$this->database = $database;
		$this->passwords = $passwords;
	}

	public function authenticate(string $email, string $password): SimpleIdentity
	{
		$rowInstructor = $this->database->table('osoby')->where('email', $email)->fetch();
		$rowSchool = $this->database->table('skoly')->where('email', $email)->fetch();

		if($rowInstructor) {
			// akutalizace hashe pokud ze zmenily definovane parametry hashovani
			if(password_needs_rehash($rowInstructor->heslo, PASSWORD_HASH_ALGO, PASSWORD_HASH_OPTIONS))
			{
				$this->database->table('osoby')->where('email = ?', $email)->update([
					'heslo' => password_hash($password, PASSWORD_HASH_ALGO, PASSWORD_HASH_OPTIONS),
				]);
				$rowInstructor = $this->database->table('osoby')->where('email = ?', $email)->fetch();
			}

			// pokus o prihlaseni
			if($this->passwords->verify($password, $rowInstructor->heslo)) {
                $this->database->table('osoby')->where('email = ?', $email)->update([
					'posledni_prihlaseni' => date('Y-m-d H:i:s'),
				]);
				return new SimpleIdentity(
					$rowInstructor->ID,
					'instructor', // nebo pole více rolí
					['email' => $rowInstructor->email]
				);
			} else {
				throw new Nette\Security\AuthenticationException('Invalid password.');
			}
		} else if ($rowSchool) {
			// akutalizace hashe pokud ze zmenily definovane parametry hashovani
			if(password_needs_rehash($rowSchool->heslo, PASSWORD_HASH_ALGO, PASSWORD_HASH_OPTIONS))
			{
				$this->database->table('skoly')->where('email = ?', $email)->update([
					'heslo' => password_hash($password, PASSWORD_HASH_ALGO, PASSWORD_HASH_OPTIONS),
				]);
				$rowSchool = $this->database->table('skoly')->where('email = ?', $email)->fetch();
			}

			// pokus o prihlaseni
			if($this->passwords->verify($password, $rowSchool->heslo)) {
                $this->database->table('skoly')->where('email = ?', $email)->update([
					'posledni_prihlaseni' => date('Y-m-d H:i:s'),
				]);
				return new SimpleIdentity(
					$rowSchool->ID,
					'school', // nebo pole více rolí
					['email' => $rowSchool->email]
				);
			} else {
				throw new Nette\Security\AuthenticationException('Invalid password.');
			}
		} else {
			throw new Nette\Security\AuthenticationException('User not found.');
		}
	}
}
