<?php

namespace AppBundle\Controller\Admin;

use AppBundle\Entity\Voucher;
use AppBundle\Entity\VoucherHistory;
use AppBundle\Form\Type\VoucherType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class VoucherController extends Controller
{
    /**
     * @Template()
     *
     * @param Request $request
     * @return array
     */
    public function listAction(Request $request)
    {
        $em = $this->getDoctrine();
        $query = $em->getRepository('AppBundle:Voucher')->getListQuery();

        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
            $query,
            $request->query->get('page', 1),
            20,
            array('defaultSortFieldName' => 'v.name', 'defaultSortDirection' => 'desc')
        );

        return array(
            'pagination' => $pagination
        );
    }

    /**
     * @param Request $request
     * @return array
     */
    public function createAction(Request $request)
    {
        $voucher = new Voucher();
        $form = $this->createForm(new VoucherType(), $voucher);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($voucher);

            $voucherHistory = new VoucherHistory();
            $voucherHistory
                ->setName($voucher->getName())
                ->setCode($voucher->getCode())
                ->setValue($voucher->getValue())
                ->setIsActive($voucher->getIsActive())
                ->setUser($this->getUser())
                ->setVoucher($voucher);

            $em->persist($voucherHistory);
            $em->flush();

            return $this->redirect($this->generateUrl('app_admin.voucher.list'));
        }

        return $this->render(
            'AppBundle:Admin/Voucher:form.html.twig',
            array(
                'form' => $form->createView()
            )
        );
    }

    /**
     * @param Request $request
     * @param Voucher $voucher
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function editAction(Request $request, Voucher $voucher)
    {
        if($voucher->getIsRemoved()) {
            throw new AccessDeniedException();
        }

        $voucherClone = clone($voucher);
        $form = $this->createForm(new VoucherType(), $voucher);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->flush();

            $this->saveVoucherEditHistory($voucherClone, $voucher);

            return $this->redirect($this->generateUrl('app_admin.voucher.list'));
        }

        return $this->render(
            'AppBundle:Admin/Voucher:form.html.twig',
            array(
                'voucher' => $voucher,
                'form' => $form->createView()
            )
        );
    }

    /**
     * @param Voucher $voucher
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function removeAction(Voucher $voucher)
    {
        if($voucher->getIsRemoved()) {
            throw new AccessDeniedException();
        }

        $em = $this->getDoctrine()->getManager();
        $voucher->setIsRemoved(true);

        $voucherHistory = new VoucherHistory();
        $voucherHistory
            ->setUser($this->getUser())
            ->setVoucher($voucher)
            ->setIsRemoved(true);

        $em->persist($voucherHistory);
        $em->flush();

        return $this->redirect($this->generateUrl('app_admin.voucher.list'));
    }

    /**
     * @Template()
     *
     * @param Request $request
     * @param Voucher $voucher
     * @return array
     */
    public function historyAction(Request $request, Voucher $voucher)
    {
        $em = $this->getDoctrine();
        $query = $em->getRepository('AppBundle:VoucherHistory')->getHistoryListQuery($voucher);

        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
            $query,
            $request->query->get('page', 1),
            20,
            array('defaultSortFieldName' => 'vh.createdAt', 'defaultSortDirection' => 'desc')
        );

        return array(
            'pagination' => $pagination
        );
    }

    /**
     * @Template()
     *
     * @param Request $request
     * @return array
     */
    public function removedListAction(Request $request)
    {
        $em = $this->getDoctrine();
        $query = $em->getRepository('AppBundle:Voucher')->getRemovedListQuery();

        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
            $query,
            $request->query->get('page', 1),
            20,
            array('defaultSortFieldName' => 'v.updatedAt', 'defaultSortDirection' => 'desc')
        );

        return array(
            'pagination' => $pagination
        );
    }

    /**
     * @param Voucher $oldVoucher
     * @param Voucher $voucher
     */
    private function saveVoucherEditHistory(Voucher $oldVoucher, Voucher $voucher)
    {
        $isEdited = false;
        $voucherHistory = new VoucherHistory();

        if($oldVoucher->getName() != $voucher->getName()) {
            $voucherHistory->setName($voucher->getName());
            $isEdited = true;
        }

        if($oldVoucher->getCode() != $voucher->getCode()) {
            $voucherHistory->setCode($voucher->getCode());
            $isEdited = true;
        }

        if($oldVoucher->getValue() != $voucher->getValue()) {
            $voucherHistory->setValue($voucher->getValue());
            $isEdited = true;
        }

        if($oldVoucher->getIsActive() != $voucher->getIsActive()) {
            $voucherHistory->setIsActive($voucher->getIsActive());
            $isEdited = true;
        }

        if($isEdited) {
            $em = $this->getDoctrine()->getManager();
            $voucherHistory
                ->setUser($this->getUser())
                ->setVoucher($voucher);

            $em->persist($voucherHistory);
            $em->flush();
        }
    }
}
