<?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\Admin;

use App\Entity\Feeds\Feed;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Flash\Messages;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Diactoros\Response\RedirectResponse;
use Zend\Hydrator\DelegatingHydrator;


/**
 * Class Feeds
 * @package App\Action\Admin
 */
class Feeds extends Common
{
    const ACTION_CREATE = 'create';
    const ACTION_EDIT = 'edit';
    const ACTION_LIST = 'list';
    
    /**
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @param callable|null $next
     * @return HtmlResponse
     */
    function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
    {
        
        if($request->getMethod() == 'POST') {
            
            try {
                switch ($request->getAttribute('action')) {
                    case self::ACTION_CREATE:    
                        $response = $this->create($request);
                        break;
                    case self::ACTION_EDIT:
                        $response = $this->edit($request);
                        break;
                    default:                    
                }
            } catch(\Exception $e) {
                $data = [
                    'result' => false,
                    'msg' => $e->getMessage(),                    
                ];
                $response = new JsonResponse($data);
            }                        
            return $response;            
        } elseif($request->getAttribute('action') == self::ACTION_CREATE || $request->getAttribute('action') == self::ACTION_EDIT) {
            
            $feed_id = $request->getAttribute('id');
            
            if ($feed_id) {
                
                /** @var \App\Model\Feeds $feedsModel */
                $feedsModel = $this->container->get(\App\Model\Feeds\Feeds::class);
                $feed = $feedsModel->findById($feed_id);
                
            }
            
            /** @var \App\Model\Currencies $currencyModel */
            $currencyModel = $this->container->get(\App\Model\Currencies::class);
            $currencies = [];
            foreach($currencyModel->findAll() as $currency) {
                $currencies[$currency->getCode()] = $currency->getName();
            }
            
            /** @var \App\Model\Users $usersModel */
            $usersModel = $this->container->get(\App\Model\Users::class);
            $all_users = $usersModel->findAll();
            
            /** @var \App\Model\Sites $sitesModel */            
            $sitesModel = $this->container->get(\App\Model\Sites::class);
            $sites = $sitesModel->findAll()->toArray();
            
            $sites_users = [];
            foreach($sites as $site) {
                $sites_users[] = $site['users_id'];
            }
            $sites_users = array_unique($sites_users);
            
            $users = [];
            foreach($all_users as $user) {
                $user_id = $user->getId();
                if (!in_array($user_id, $sites_users)) {
                    $users[$user_id] = $user->getFullname();
                }
            }
            
            $response =  new HtmlResponse($this->template->render('adm::feeds/feed', [
                'lang' => $request->getAttribute('layoutInfo')->getLang(),
                'feed' => $feed,
                'users' => $users,
                'currencies' => $currencies,
                'formats' => $this->container->get('config')['feed_conf']['formats']
            ]));
            return $response;
            
        } else {

            /** @var \App\Model\Sites $sitesModel */
            $usersModel = $this->container->get(\App\Model\Users::class);
            
            /** @var \App\Model\Feeds $feedsModel */
            $feedsModel = $this->container->get(\App\Model\Feeds\Feeds::class);
            $feeds = $feedsModel->findAll()->toArray();
            
            foreach ($feeds as $key => $feed) {
                $user = $usersModel->findById($feed['clientid']);
                if ($user) {
                    $feeds[$key]['clientid'] = $user->getFullname();
                }
            }
            
            $response =  new HtmlResponse($this->template->render('adm::feeds/list', [
                'lang' => $request->getAttribute('layoutInfo')->getLang(),
                'feeds' => $feeds,
            ]));
            
            return $response;
            
        }
        
    }

    
    /**
     * @param ServerRequestInterface $request
     * @return HtmlResponse|RedirectResponse
     */
    private function create(ServerRequestInterface $request) 
    {
        /** @var \App\Model\Feeds $feedsModel */
        $feedsModel = $this->container->get(\App\Model\Feeds\Feeds::class);
        
        /** @var DelegatingHydrator $hydrator */
        $hydrator = $this->container->get(DelegatingHydrator::class);
        
        $data = $request->getParsedBody();

        $data = array(
            'title' => (trim($data['title']) != "") ? trim($data['title']) : NULL,
            'active' => (bool)$data['active'],
            'clientid' => (int)$data['clientid'],
            'url' => $data['url'],
            'format' => $data['format'],
            'defaultcur' => $data['defaultcur'],
        );
        
        $feed = $hydrator->hydrate($data, new Feed());
        
        // Проверка наличия фида с таким же названием:
        if(($existed = $feedsModel->findOne(['title' => $data['title']]))) {
            throw new \Exception(sprintf('Feed with title &lt;%s&gt; already exists', $data['title']));
        }
        
        $result = $feedsModel->saveRetarg($feed);
        if(!$result) {
            throw new \Exception('DB error');
        }                 
        
        $response = new JsonResponse([
            'result' => true,
            'redirect' => $this->router->generateUri('adm.feed.edit', [
                'lang' => $request->getAttribute('layoutInfo')->getLang(),
                'id' => $result,
            ])
        ]);
        return $response;        
        
    }
    
    private function edit(ServerRequestInterface $request)
    {
        /** @var \App\Model\Feeds $feedsModel */
        $feedsModel = $this->container->get(\App\Model\Feeds\Feeds::class);
        
        /** @var DelegatingHydrator $hydrator */
        $hydrator = $this->container->get(DelegatingHydrator::class);
        
        $data = $request->getParsedBody();
        $feed_id = $request->getAttribute('id');
        
        $feed = $feedsModel->findById($feed_id);
        if(!$feed) {
            throw new \Exception('Feed not found');
        }

        //return new JsonResponse($data);
        
        $data['title'] = (trim($data['title']) != "") ? trim($data['title']) : NULL;
        $feed->setTitle($data['title']);
        $feed->setActive((bool)$data['active']);
        $feed->setClientid((int)$data['clientid']);
        $feed->setUrl($data['url']);
        $feed->setFormat($data['format']);
        $feed->setDefaultcur($data['defaultcur']);
        
        // Проверка наличия фида с таким же названием:
        if(($existed = $feedsModel->findOne(['title' => $data['title']]))) {
            if($existed->getId() != $feed->getId()) {
                throw new \Exception(sprintf('Feed with title &lt;%s&gt; already exists', $data['title']));
            }
        }
        
        //$result = $feedsModel->save($feed);
        $result = $feedsModel->saveRetarg($feed);
        
        if(!$result) {
            throw new \Exception('DB error');
        }

        $response = new JsonResponse([
            'result' => true,
            'redirect' => $this->router->generateUri('adm.feed.edit', [
                'lang' => $request->getAttribute('layoutInfo')->getLang(),
                'id' => $feed_id,
            ])
        ]);
        return $response;        
    }

    
}