<?php

namespace KupShop\UserBundle\View;

use KupShop\KupShopBundle\Views\View;
use KupShop\UserBundle\Security\LegacyPasswordEncoder;

class PasswordView extends View
{
    protected $template = 'user.password.tpl';

    protected $encoder;

    public function __construct(LegacyPasswordEncoder $encoder)
    {
        if (!\User::getCurrentUser()) {
            redirection('LOGIN');
        }

        $this->encoder = $encoder;
    }

    public function getTitle()
    {
        return translate('title', 'user.password');
    }

    public function getBodyVariables()
    {
        if (getVal('acn') == 'changePassword') {
            $this->handleChangePassword();
        }

        return parent::getBodyVariables();
    }

    public function handleChangePassword()
    {
        $user = \User::getCurrentUser();

        $oldPassword = getVal('oldPassword');
        if ($user->passw != '' && $oldPassword !== null) {
            if (!$this->encoder->isPasswordValid($user->passw, $oldPassword, '')) {
                $this->addErrorMessage(translate('passwordChangeErrorNoMatch', 'user.password'));

                return;
            }
        }

        $newPassword = getVal('newPassword');
        if ($user->sanitizePassword($newPassword)) {
            $this->addErrorMessage(translate('passwordChangeErrorWeak', 'user.password'));

            return;
        }

        $user->updatePassword($newPassword);

        $this->addSuccessMessage(translate('passwordChanged', 'user.password'));
    }
}
