<?php
namespace App\Controller;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Views\Blade as View;
use App\Contract\Auth as sAuth;

class Auth
{
	public function login(ServerRequestInterface $request, ResponseInterface $response, View $view): ResponseInterface
	{
		return $view->render($response, 'auth.login');
	}
	public function do_login(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
	{
		$post = $request->getParsedBody();
        $name = $post['name'];
		$password = $post['password'];
		$bool = sAuth::login($name, $password);
		if ($bool) {
			return $response->withStatus(301)->withHeader('Location', '/');
		}
		return $response->withStatus(301)->withHeader('Location', '/auth/login');
	}
	public function logout(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
	{
		sAuth::logout();
		return $response
			->withStatus(301)
			->withHeader('Location', '/');
	}
	public function check_pass(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
	{
		if (\password_verify(post('password'), sAuth::User()->password)) {
			$response->getBody()->write('OK');
		} else {
			$response->getBody()->write('KO');
		}
		return $response;
	}
	public function change_pass(ServerRequestInterface $request, ResponseInterface $response, View $view): ResponseInterface
	{
		return $view->render($response, 'auth.change_pass');
	}
	public function do_change_pass(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
	{
        $post = $request->getParsedBody();
		if (\password_verify($post['old'], sAuth::User()->password)) {
			if ($post['new'] == $post['new2']) {
				$user = sAuth::User();
				$user->password($post['new']);
				$user->save();
				return $response->withStatus(301)->withHeader('Location', '/');
			}
		}
		return $response->withStatus(301)->withHeader('Location', '/auth/change_pass');
	}
}
