<?php
/**
 * Created by PhpStorm.
 * User: eater
 * Date: 4/2/16
 * Time: 1:54 PM
 */

namespace Eater\Glim\Handler\Login;


use Eater\Glim\Handler\Main;
use Eater\Glim\Service\User;

class Action extends Main
{
    public function handle()
    {
        $username = $this->post('username');
        $password = $this->post('password');

        /* @var User $user */
        $user = $this->get('user');
        /* @var \Aura\Session\Session $session */
        $session = $this->get('session');
        $segment = $session->getSegment('main');

        $loggedUser = $user->login($username, $password);

        if ($loggedUser === null) {
            $segment->setFlash("error", "Login failed, username or password are incorrect");

            return $this->redirect('/login');
        }

        $segment->set('userId', $loggedUser->getId());

        $afterLogin = $segment->get('afterLogin');
        $segment->set('afterLogin', null);

        if ($afterLogin !== null) {
            return $this->redirect($afterLogin);
        }

        return $this->redirect('/panel');
    }
}