<?php

namespace Origo\Controller;

use Origo\Controller\ControllerInterface;
use Origo\Services\Request;
use Origo\Services\Renderer;
use Origo\Services\Template;
use Origo\Entity\User;

class UserLoginController implements ControllerInterface {

  private $request;
  private Renderer $renderer;

  public function __construct() {
    $this->request = new Request();
    $this->renderer = new Renderer();
  }

  public function getResponse(): string {
    $username = $this->request->post('username') ?? FALSE;
    $password = $this->request->post('password') ?? FALSE;
    $pw_hash = hash('sha256', $password);
    // Check if user can login.
    $user = new User();
    $session_id = $user->login($username, $pw_hash);

    if (!$session_id) {
      return $this->renderer->render403();
    }
    else {
      header("Location: /dashboard");
      die();
    }
  }
}
