<?php

namespace Eater\Glim\Handler\Verify;

use Aura\Session\Segment;
use Eater\Glim\Handler\Session;
use Eater\Glim\Model\EmailAddressQuery;
use Eater\Glim\Model\User;

class Show extends Session
{
    protected $shouldHaveUser = false;

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

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

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

        $user = $this->getUser();
        
        if ($user !== null) {
            
            $email = $user->getEmailAddressRelatedByEmail();
            
            if ($email === null || $email->getId() !== $id || $email->getVerified()) {
                return $this->notFound();
            }
            
            /* @var \Aura\Session\Session $session */
            $session = $this->get('session');
            $segment = $session->getSegment('main');
            $segment->set('userId', null);
            $this->setUser(null);
        }

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

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

        return $this->render('login.html.twig', [
            'message' => 'Please login to verify your email',
            'action' => $this->getRequest()->getUri()->getPath()
        ]);
    }
}