<?php
namespace Incoviba\Controller;

use PDOException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Repository;
use Incoviba\Service;

class Login
{
    public function form(ServerRequestInterface $request, ResponseInterface $response, View $view, Service\Login $service): ResponseInterface
    {
        if ($service->isIn()) {
            return $response->withStatus(301)->withHeader('Location', $view->get('urls')->base);
        }
        return $view->render($response, 'login.form');
    }
    public function login(ServerRequestInterface $request, ResponseInterface $response, Repository\User $userRepository, Service\Login $service): ResponseInterface
    {
        $body = $request->getParsedBody();
        $user = $userRepository->fetchByName($body['name']);
        $output = [
            'name' => $user->name,
            'login' => false
        ];
        if ($user->validate($body['password'])) {
            $output['login'] = $service->login($user);
        }
        $response->getBody()->write(json_encode($output));
        return $response->withHeader('Content-Type', 'application/json');
    }
    public function logout(ServerRequestInterface $request, ResponseInterface $response, Repository\Login $loginRepository, Service\Login $service): ResponseInterface
    {
        $output = [
            'name' => '',
            'logout' => false
        ];
        try {
            $user = $service->getUser();
            $output = [
                'name' => $user->name,
                'logout' => $service->logout($user)
            ];
        } catch (PDOException) {}
        $response->getBody()->write(json_encode($output));
        return $response->withHeader('Content-Type', 'application/json');
    }
}
