<?php

namespace App\Controller;

use App\Enum\CurrencyEnum;
use App\Form\Type\ListOperationFormType;
use App\Utils\OperationUtils;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security as Secur;

class OperationsController extends AbstractController
{
    protected $em;
    protected $paginator;
    protected $operationUtils;
    protected $security;
    private $session;


    public function __construct(EntityManagerInterface $em, PaginatorInterface $paginator, OperationUtils $operationUtils, Secur $security, SessionInterface $session)
    {
        $this->em = $em;
        $this->paginator = $paginator;
        $this->operationUtils = $operationUtils;
        $this->security = $security;
        $this->session = $session;
    }

    /**
     * @Route("/show/operations/{currency}", name="show_operations", defaults={"currency": "emlc"})
     */
    public function showOperationsAction(Request $request, $currency = CurrencyEnum::CURRENCY_MLC)
    {
        if (empty($this->getUser())) {
            return $this->redirectToRoute('index');
        }

        //Prepare query depending on user role
        $user = $this->security->getUser();
        $role = "";
        if (null != $this->session->get('_prestagere') && $user->isGranted('ROLE_PRESTATAIRE')) {
            $role = "ROLE_PRESTATAIRE";
        } elseif (null != $user->getAdherent() && $user->isGranted('ROLE_ADHERENT')) {
            $role = "ROLE_ADHERENT";
        } elseif (null != $this->session->get('_comptoirgere') && $user->isGranted('ROLE_COMPTOIR')) {
            $role = "ROLE_COMPTOIR";
        } elseif (null != $this->session->get('_groupegere') && $user->isGranted('ROLE_GESTION_GROUPE')) {
            $role = "ROLE_GESTION_GROUPE";
        }

        if (!in_array($currency, CurrencyEnum::getAvailableTypes())) {
            throw new \Exception('Opération impossible ! Type de currency  ' . $currency . ' inexistant');
        }

        $datemin = new \DateTime('first day of this month');
        $datemin->setTime(0, 0, 0);
        $datemax = new \DateTime('now');
        $form = $this->createForm(ListOperationFormType::class, null, array("role" => $role));
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if (!$form->get('submit')->isClicked()) {
                $format = 'csv'; // CSV by default
                if ($form->get('json')->isClicked()) {
                    $format = 'json';
                } elseif ($form->get('csv')->isClicked()) {
                    $format = 'csv';
                } elseif ($form->get('xls')->isClicked()) {
                    $format = 'xls';
                } elseif ($form->get('xml')->isClicked()) {
                    $format = 'xml';
                }

                return $this->forward('App\Controller\FluxController::exportUserOperationAction', [
                    'format' => $format,
                    'currency' => $currency,
                ]);
            }
        }

        $query = $this->operationUtils->getUserOperationsByCurrency($request, $currency);
        $operations = [];
        if (null !== $query) {
            $operations = $this->paginator->paginate(
                $query, /* query NOT result */
                $request->query->getInt('page', 1)/*page number*/ ,
                20/*limit per page*/
            );
            $operations->setCustomParameters([
                'align' => 'center',
            ]);
        }

        return $this->render('@kohinos/flux/operations.html.twig', [
            'operations' => $operations,
            'currency' => $currency,
            'searchForm' => $form->createView(),
        ]);
    }
}
