<?php

/*
 * kohinos_cooperatic
 * Copyright (C) 2019-2020  ADML63
 * Copyright (C) 2020- Cooperatic
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
namespace App\Controller;

use App\Entity\Prestataire;
use App\Entity\Rubrique;
use App\Entity\TransactionPrestataireAdherent;
use App\Entity\TransfertPrestataireSiege;
use App\Entity\TypePrestataire;
use App\Entity\AchatMonnaiePrestataire;
use App\Entity\Payment;
use App\Form\Type\GroupePrestataireInscriptionFormType;
use App\Form\Type\PrestataireInfosFormType;
use App\Form\Type\TransactionPrestataireAdherentFormType;
use App\Form\Type\TransfertPrestataireSiegeFormType;
use App\Form\Type\AchatMonnaiePrestataireFormType;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Translation\TranslatorInterface;

class UserPrestataireController extends FluxController
{
    /**
     * @Route("/prestataireinfos", name="prestataire_infos")
     * @IsGranted("ROLE_PRESTATAIRE")
     */
    public function prestataireInfosAction(Request $request)
    {
        $form = $this->createForm(PrestataireInfosFormType::class, $this->session->get('_prestagere'));
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->em->persist($form->getData());
            $this->em->flush();
            $this->addFlash(
                'success',
                $this->translator->trans('Infos du prestataire modifiées !')
            );
            $referer = $request->headers->get('referer');
            if ($referer && !$request->isXmlHttpRequest()) {
                return $this->redirect($referer);
            } elseif (!$request->isXmlHttpRequest()) {
                return new Response('', Response::HTTP_BAD_REQUEST);
            }
        }

        return $this->redirectToRoute('index');
    }

    /**
     * @Route("/prestatairegroupes/inscription", name="groupeprestataire_inscription")
     * @IsGranted("ROLE_PRESTATAIRE")
     */
    public function groupePrestataireInscriptionAction(Request $request)
    {
        //#180: at this point, the Prestataire entity is detached from the EntityManager (because we get it from the session)
        $presta = $this->session->get('_prestagere');
        //#180: $presta now refers to the fully managed copy returned by the merge operation.
        $presta = $this->em->merge($presta);

        $form = $this->createForm(GroupePrestataireInscriptionFormType::class, $presta);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $prestataire = $form->getData();
            $this->em->persist($prestataire);
            $this->em->flush();
            $this->addFlash(
                'success',
                $this->translator->trans('Information bien prise en compte !')
            );
            if ($request->isXmlHttpRequest()) {
                return new JsonResponse(array('status' => 'success'));
            } else {
                $referer = $request->headers->get('referer');
                if ($referer && !$request->isXmlHttpRequest()) {
                    return $this->redirect($referer);
                } elseif (!$request->isXmlHttpRequest()) {
                    return new Response('', Response::HTTP_BAD_REQUEST);
                }
            }
        }

        return $this->redirectToRoute('index');
    }

    /**
     * @Route("/prestataire/transaction/{type}/", name="transactionPrestataireAdherent", defaults={"type": "adherent"})
     * @Route("/prestataire/transaction/{type}/", name="transactionPrestatairePrestataire", defaults={"type": "prestataire"})
     * @IsGranted("ROLE_PRESTATAIRE")
     */
    public function transactionPrestataireAction($type, Request $request)
    {
        $entityName = 'App\Entity\TransactionPrestataire'.ucwords($type);
        $entity = new $entityName();
        $entity->setOperateur($this->getUser());
        $entity->setExpediteur($this->session->get('_prestagere'));
        $form = $this->createForm('App\Form\Type\TransactionPrestataire'.ucwords($type).'FormType', $entity);
        return $this->manageFluxForm(
            $request,
            $form,
            $this->session->get('_prestagere')->getEcompte(),
            $this->translator->trans('Transaction bien effectuée !'),
            $this->translator->trans('Transaction à un ').$type
        );
    }


    /**
     * @Route("/prestataire/transfert/siege/", name="transactionPrestataireSiege")
     * @IsGranted("ROLE_PRESTATAIRE")
     */
    public function transfertPrestataireSiegeAction(Request $request)
    {
        $entity = new TransfertPrestataireSiege();
        $entity->setOperateur($this->getUser());
        $entity->setExpediteur($this->session->get('_prestagere'));
        $form = $this->createForm(TransfertPrestataireSiegeFormType::class, $entity);
        return $this->manageFluxForm(
            $request,
            $form,
            $this->session->get('_prestagere')->getEcompte(),
            $this->translator->trans('Reconversion envoyée, elle sera validée lorsque le virement sera effectué !'),
            $this->translator->trans('Reconversion de monnaie au siège')
        );
    }

    /**
     * @Route("/prestataire/achat-monnaie/", name="achatMonnaiePrestataire")
     * @IsGranted("ROLE_PRESTATAIRE")
     */
    public function achatMonnaiePrestataireAction(Request $request)
    {
        if (empty($this->getUser()) || empty($this->session->get('_prestagere'))) {
            return $this->redirectToRoute('index');
        }

        $entity = new AchatMonnaiePrestataire();
        $form = $this->createForm(AchatMonnaiePrestataireFormType::class, $entity);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
          return $this->preparePaymentAction(
            $form,
            Payment::TYPE_ACHAT_MONNAIE_PRESTA
          );
        }

        return $this->render('flux/transaction.html.twig', [
            'form' => $form->createView(),
            'title' => $this->translator->trans('Achat de monnaie locale')
        ]);
    }

}