<?php

namespace KupShop\CommentsBundle\Controller;

use KupShop\CommentsBundle\Comment;
use KupShop\CommentsBundle\Util\CommentsUtil;
use KupShop\CommentsBundle\View\CommentAddedView;
use KupShop\CommentsBundle\View\CommentFormView;
use KupShop\CommentsBundle\View\CommentsView;
use KupShop\ContentBundle\Util\Captcha;
use KupShop\ContentBundle\View\Exception\ValidationException;
use KupShop\KupShopBundle\Views\Traits\MessagesTrait;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class CommentController extends AbstractController
{
    use MessagesTrait;

    /**
     * @Route("/_comment/get/")
     */
    public function commentsAction(Request $request, CommentsView $view): Response
    {
        $objectId = (int) $request->get('objectId');
        $type = $request->get('type');
        $page = (int) $request->get('page', 1);
        $languageId = $request->get('languageId');

        $view->setType($type)
            ->setObjectId($objectId)
            ->setLanguageId($languageId)
            ->setPage($page);

        return $view->getResponse();
    }

    /**
     * @Route("/_comment/form/")
     */
    public function commentFormAction(Request $request, CommentFormView $view): Response
    {
        $view->setData([
            'objectId' => $request->get('objectId'),
            'parentId' => $request->get('parentId'),
            'type' => $request->get('type'),
        ]);

        return $view->getResponse();
    }

    /**
     * @Route("/_comment/add/")
     */
    public function addCommentAction(
        Request $request,
        CommentsUtil $commentsUtil,
        CommentAddedView $view,
        CommentFormView $formView,
    ): Response {
        $msg = false;
        if ($this->validateCaptcha($_POST)) {
            $msg = translate('errorCaptcha', 'form');
        } elseif ($this->validateRequest($request)) {
            $msg = translate('errorRequiredMissing', 'form');
        }

        if ($msg) {
            $formView->setData(
                [
                    'objectId' => $request->get('id_product'),
                    'parentId' => $request->get('id_parent'),
                    'type' => $request->get('type'),
                    'name' => $request->get('name'),
                    'surname' => $request->get('surname'),
                    'email' => $request->get('email'),
                    'content' => $request->get('content'),
                ]
            );
            $this->addErrorMessage($msg);

            return $formView->getResponse();
        }

        $this->doAddComment($request, $commentsUtil);

        return $view->getResponse();
    }

    protected function doAddComment(Request $request, CommentsUtil $commentsUtil): Comment
    {
        $productId = $request->get('id_product');
        if ($parentId = $request->get('id_parent')) {
            $parentId = (int) $parentId;
        } else {
            $parentId = null;
        }
        $type = $request->get('type');
        $content = html_entity_decode($request->get('content'));

        $userId = null;
        if (findModule(\Modules::COMMENTS, \Modules::SUB_COMMENTS_ANONYMOUS)) {
            if (!\User::getCurrentUser() && !getAdminUser()) {
                $userId = addUserEmail($request->get('email'),
                    [],
                    ['figure' => 'N', 'name' => $request->get('name'), 'surname' => $request->get('surname')]);
            }
        }

        return $commentsUtil->addComment((int) $productId, $type, $content, $parentId, $userId);
    }

    protected function validateRequest(Request $request)
    {
        if (!\User::getCurrentUser() && !getAdminUser()) {
            if (!$request->get('email') || !$request->get('name') || !$request->get('surname')) {
                return 1;
            }
        }

        if (!$request->get('content')) {
            return 1;
        }

        return 0;
    }

    protected function validateCaptcha($data)
    {
        if (!\User::getCurrentUser() && !getAdminUser()) {
            try {
                Captcha::checkCaptcha($data);
            } catch (ValidationException $e) {
                return 1;
            }
        }

        return 0;
    }
}
