<?php

namespace KupShop\ReclamationsBundle\Controller;

use KupShop\KupShopBundle\Exception\RedirectException;
use KupShop\KupShopBundle\Routing\TranslatedRoute;
use KupShop\KupShopBundle\Views\Traits\MessagesTrait;
use KupShop\OrderingBundle\Util\Order\OrderActivationUtil;
use KupShop\OrderingBundle\Util\UserContent\UserContent;
use KupShop\ReclamationsBundle\Attachment\ReclamationPDFAttachment;
use KupShop\ReclamationsBundle\Util\ReclamationsUtil;
use KupShop\ReclamationsBundle\View\CreateReclamationView;
use KupShop\ReclamationsBundle\View\ReclamationsView;
use KupShop\ReclamationsBundle\View\ReclamationView;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ReclamationsController extends AbstractController
{
    use MessagesTrait;

    /**
     * @TranslatedRoute("/#reclamations#/#reclamations-list#/")
     */
    public function reclamationsAction(Request $request, ReclamationsView $view): Response
    {
        return $view->getResponse($request);
    }

    /**
     * @TranslatedRoute("/#reclamations#/#create_reclamation#/")
     */
    public function createReclamationAction(Request $request, CreateReclamationView $view, OrderActivationUtil $activationUtil): Response
    {
        $view->setStep('products');
        $filter = $request->get('filter', []);

        if ($request->get('nextStep')) {
            if ($request->get('item_id') && $request->get('item_pieces')) {
                throw new RedirectException(path('kupshop_reclamations_reclamations_createreclamationsummary',
                    ['item_id' => $request->get('item_id'), 'pieces' => $request->get('item_pieces')]));
            } else {
                addUserMessage(translate('error_no_items', 'returns'), 'danger');
            }
        } elseif (($id_order = $request->get('id_order')) && ($cf = $request->get('cf'))) {
            if (!$activationUtil->activateOrderWithSecurityCode($id_order, $cf)) {
                $this->addErrorMessage(
                    translate('error_order_not_found', 'returns')
                );

                return new RedirectResponse(
                    path('kupshop_returns_returns_createreturnslogin')
                );
            }

            $filter['order'] = $id_order;
        }

        $view->setFilter($filter);

        return $view->getResponse($request);
    }

    /**
     * @TranslatedRoute("/#reclamations#/#reclamation_summary#/")
     */
    public function createReclamationSummaryAction(Request $request, CreateReclamationView $view, UserContent $userContent): Response
    {
        $view->setStep('summary')->setItemId($request->get('item_id'))->setItemPieces($request->get('pieces'));

        if ($request->get('nextStep')) {
            $user_content = $userContent->getData('reclamation');
            $view->handleStep_reclamationSummary(
                $request->get('delivery'),
                $request->get('bank_account'),
                $request->get('preferred_handle_type'),
                $request->get('note'),
                $user_content
            );
        }

        return $view->getResponse($request);
    }

    /**
     * @TranslatedRoute("/#reclamations#/")
     */
    public function createReclamationLoginAction(Request $request, CreateReclamationView $view, OrderActivationUtil $activationUtil): Response
    {
        $view->setStep('login');

        // nacteni objednavky pro uzivatele bez registrace
        if ($request->isMethod('POST')) {
            if (!$activationUtil->activateFromRequest($request)) {
                $this->addErrorMessage(
                    translate('error_order_not_found', 'returns')
                );

                return new RedirectResponse(
                    path('kupshop_reclamations_reclamations_createreclamationlogin')
                );
            }

            return new RedirectResponse(
                path('kupshop_reclamations_reclamations_createreclamation')
            );
        }

        return $view->getResponse($request);
    }

    /**
     * @TranslatedRoute("/#reclamations#/{id}/", requirements={"id"="\d+"})
     */
    public function reclamationAction(Request $request, ReclamationView $view, $id, UserContent $userContent): Response
    {
        if (getVal('success') == 1) {
            $userContent->setData('reclamation', null);
        }

        $view->setReclamationId($id);

        return $view->getResponse($request);
    }

    /**
     * @TranslatedRoute("/#reclamations#/{id}/pdf/")
     */
    public function reclamationAttachmentAction(ReclamationPDFAttachment $reclamationPDFAttachment, ReclamationsUtil $reclamationsUtil, $id, Request $request): Response
    {
        if (!($reclamation = $reclamationsUtil->getReclamation($id, $request->get('cf') != $reclamationsUtil->getSecurityCode($id)))) {
            throw new RedirectException(path('kupshop_reclamations_reclamations_createreclamationlogin'));
        }

        $reclamationPDFAttachment->setReclamation($reclamation);

        try {
            $response = new Response();
            $response->headers->set('Content-Type', $reclamationPDFAttachment->getMimeType());
            $response->headers->set('Content-Disposition', 'inline; filename="'.$reclamationPDFAttachment->getFilename().'"');
            $content = $reclamationPDFAttachment->getContent();
            if (!$content) {
                throw new \UnexpectedValueException('PDF error: server returned false');
            }
            $response->setContent($content);

            return $response;
        } catch (\UnexpectedValueException $e) {
            getRaven()->captureException($e);

            return new Response('Přílohu se nepodařilo vygenerovat, zkuste to znovu.');
        }
    }
}
