<?php

namespace Eater\Glim\Handler\Verify;

use Eater\Glim\Handler\Session;
use Eater\Glim\Model\EmailAddressQuery;
use Eater\Glim\Service\User;

class Action extends Session
{
    protected $shouldHaveUser = false;

    public function handle()
    {
        $verify = $this->attr('verify');
        $verifyParts = explode('-', $verify, 2);

        if (count($verifyParts) < 2) {
            return $this->notFound();
        }

        $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("message", "Login failed, username or password are incorrect");
            $segment->setFlash('username', $username);

            return $this->redirect($this->getRequest()->getUri()->getPath());
        }

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

        $id = intval($verifyParts[0]);
        $verification = $verifyParts[1];


        $email = $loggedUser->getEmailAddressRelatedByEmail();

        if ($email === null || $email->getId() !== $id || $email->getVerified()) {
            return $this->notFound();
        }

        $email = EmailAddressQuery::create()->findOneById($id);

        if ($email === null || $email->getVerified() || $email->getVerification() !== $verification) {
            return $this->notFound();
        }

        $email->setVerified(true);
        $email->save();

        $segment->setFlash('message', 'Successfully verified "' . $email->getAddress() .'"');

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