<?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
    {
        $redirect_uri = $request->hasHeader('Referer') ? $request->getHeaderLine('Referer') : $view->get('urls')->base;
        if ($service->isIn()) {
            $redirect_uri = str_replace('/login', '', $redirect_uri);
            return $response->withStatus(301)->withHeader('Location', $redirect_uri);
        }
        if ($request->hasHeader('X-Redirect-URI')) {
            $redirect_uri = $request->getHeaderLine('X-Redirect-URI');
        }
        $query = $request->getQueryParams();
        if (isset($query['url'])) {
            $redirect_uri = base64_decode(urldecode($query['url']));
        }
        return $view->render($response, 'login.form', compact('redirect_uri'));
    }
    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');
    }
}
