<?php
/**
 * Copyright (c) 2016 Serhii Borodai <clarifying@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 *
 */

namespace App\Action\User;


use App\Action\Common;
use App\Authentication\UserService;
use App\Entity\User;
use App\Model\Users;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Hydrator\DelegatingHydrator;

/**
 * Class Profile
 * @package App\Action\User
 */
class Profile extends Common
{

    /**
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @param callable|null $next
     * @return ResponseInterface|HtmlResponse|JsonResponse
     */
    function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
    {
        /** @var Users $usersModel */
        $usersModel = $this->container->get(Users::class);
        
        /** @var UserService $auth */
        $auth = $this->container->get(UserService::class);

        switch ($request->getMethod()) {
            case 'POST':
                $msg = array();
                /** @var User $userFromDb */
                $userFromDb = $usersModel->findById($auth->getIdentity()->getId());
                /** @var DelegatingHydrator $hydrator */
                $hydrator = $this->container->get(DelegatingHydrator::class);
                $data = $request->getParsedBody();
                //@todo implement validation
                
                if (isset($data['currency'])) {
                    
                    $result = false;
                }
                else
                {
                    $result = true;                
                    if (isset($data['new-password']) && $data['new-password']) {
                        if (!password_verify($data['password'], $userFromDb->getPassword())) {
                            $result = false;
                            $msg['text'] = 'old password incorrect';
                        }
                    }
                    if ($result) {                                                         
                        if (isset($data['new-password']) && !$data['new-password']) {
                            unset($data['new-password']);
                        } else {
                            $userFromDb->setPassword($usersModel->hashPassword($data['new-password']));
                        }

                        /** @var User $newUserData */
                        $validator = new \App\Validator\User($hydrator);
                        if ($validator->isValid($userFromDb)) {
                            $result = $usersModel->save($userFromDb);                       
                            if ($result) {
                                $msg['text'] = 'success';
                            } else {
                                $msg['text'] = 'db error';
                            }
                        } else {
                            $result = false;
                            $msg['text'] = $validator->getMessages();
                        }
                    }
                }
                

                $response = new JsonResponse(['result' => $result, 'msg' => $msg]);
                break;
            case 'GET':
                $userId = $auth->getIdentity()->getId();
                
                $user = $usersModel->findById($userId);
                
                $currencyModel = $this->container->get(\App\Model\Currencies::class);
                $currencies = array();
                foreach($currencyModel->findAll() as $currency) {
                    $currencies[$currency->getCode()] = $currency->getName();
                }
                $currentCurencyCode = $user->getCurrencyCode();
                
                $response = new HtmlResponse($this->template->render('app::user/profile', [
                    'user' => $user, 
                    'lang' => $request->getAttribute('layoutInfo')->getLang(),
                    'currencies' => $currencies,
                    'currency' => ['code' => $currentCurencyCode, 'name' => $currencies[$currentCurencyCode]]
                ]));
                break;
        }

        return $response;
    }
}