<?php
namespace Incoviba\Service;

use DateTimeInterface;
use DateTimeImmutable;
use DateInterval;
use Exception;
use PDOException;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Repository;
use Incoviba\Model;
use PhpParser\Node\Expr\AssignOp\Mod;
use function random_bytes;
use function password_hash;
use function setcookie;

class Login
{
    public function __construct(protected Repository\Login $repository, protected string $cookie_name, protected int $max_login_time, protected string $domain = '', protected string $path = '', protected string $cookie_separator = ':')
    {
        $this->loadCookie();
    }

    protected string $selector = '';
    protected string $token = '';

    public function isIn(): bool
    {
        try {
            $login = $this->repository->fetchActiveBySelector($this->selector);
            if (!$this->validToken($login)) {
                return false;
            }
            $now = new DateTimeImmutable();
            if ($login->dateTime->add(new DateInterval("PT{$this->max_login_time}H")) > $now) {
                return true;
            }
        } catch (PDOException|EmptyResult) {
        }
        return false;
    }
    public function getUser(): Model\User
    {
        $login = $this->repository->fetchActiveBySelector($this->selector);
        if (!$this->validToken($login)) {
            throw new Exception('User not found');
        }
        return $login->user;
    }

    public function login(Model\User $user): bool
    {
        try {
            $login = $this->repository->fetchActiveByUser($user->id);
            $this->logout($login->user);
        } catch (PDOException|EmptyResult) {
        }

        try {
            $now = new DateTimeImmutable();
            $login = $this->repository->create([
                'user_id' => $user->id,
                'time' => $now->format('Y-m-d H:i:s'),
                'status' => 1
            ]);
            list('selector' => $selector, 'token' => $token) = $this->generateToken($login);
            $login->selector = $selector;
            $login->token = password_hash($token, PASSWORD_DEFAULT);
            $this->repository->save($login);
            $this->saveCookie($selector, $token, $login->dateTime->add(new DateInterval("PT{$this->max_login_time}H")));
            return true;
        } catch (PDOException|Exception) {
            return false;
        }
    }
    public function logout(Model\User $user): bool
    {
        $this->removeCookie();
        try {
            $logins = $this->repository->fetchByUser($user->id);
        } catch (PDOException) {
            return true;
        }
        try {
            foreach ($logins as $login) {
                $this->repository->edit($login, ['status' => 0]);
            }
            return true;
        } catch (PDOException) {
            return false;
        }
    }

    protected function loadCookie(): void
    {
        if (!isset($_COOKIE[$this->cookie_name])) {
            return;
        }
        $cookie = $_COOKIE[$this->cookie_name];
        list($this->selector, $this->token) = explode($this->cookie_separator, $cookie);
    }
    protected function saveCookie(string $selector, string $token, DateTimeInterface $expires): void
    {
        setcookie(
            $this->cookie_name,
            implode($this->cookie_separator, [$selector, $token]),
            $expires->getTimestamp(),
            $this->path,
            $this->domain
        );
        $this->selector = $selector;
        $this->token = $token;
    }
    protected function removeCookie(): void
    {
        setcookie(
            $this->cookie_name,
            '',
            (new DateTimeImmutable())->getTimestamp(),
            $this->path,
            $this->domain
        );
    }

    protected function validToken(Model\Login $login): bool
    {
        return password_verify($this->token, $login->token);
    }
    protected function generateToken(Model\Login $login)
    {
        $selector = bin2hex(random_bytes(12));
        $token = bin2hex(random_bytes(20));
        return ['selector' => $selector, 'token' => $token];
    }
}
