<?php

namespace App\Controller;

use App\Entity\Flux;
use App\Entity\Prestataire;
use App\Entity\Rubrique;
use App\Entity\TransactionPrestataireAdherent;
use App\Entity\TransfertPrestataireSiege;
use App\Entity\TypePrestataire;
use App\Form\Type\GroupePrestataireInscriptionFormType;
use App\Form\Type\PrestataireInfosFormType;
use App\Form\Type\TransactionPrestataireAdherentFormType;
use App\Form\Type\TransfertPrestataireSiegeFormType;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Sonata\Exporter\Handler;
use Sonata\Exporter\Source\DoctrineORMQuerySourceIterator;
use Sonata\Exporter\Writer\CsvWriter;
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ée !')
            );
            $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)
    {
        $form = $this->createForm(GroupePrestataireInscriptionFormType::class, $this->session->get('_prestagere'));
        $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')->getCompte(),
            $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')->getCompte(),
            $this->translator->trans('Reconversion envoyée, elle sera validée lorsque le virement sera effectué !'),
            $this->translator->trans('Reconversion de monnaie au siège')
        );
    }
    
    /**
     * Export all transferts / transactions for prestataire
     *
     * @param  Request $request Request
     * @param  String  $format  Format of export ('json', 'xml', 'csv', 'xls')
     * @Route("/prestataire/export/{format}/", name="exportPrestaFlux", defaults={"format": "csv"})
     * @IsGranted("ROLE_PRESTATAIRE")
     */
    public function exportFluxAction(Request $request, $format = 'csv')
    {
        // Prepare the data source
        $query = $this->em->getRepository(Flux::class)->getQueryByPrestataire($this->session->get('_prestagere'));
        $fields = ['expediteur', 'destinataire', 'type', 'parenttype', 'montant', 'moyen', 'operateur'];
        $source = new DoctrineORMQuerySourceIterator($query, $fields);

        $filename = sprintf(
            'export_flux_%s.%s',
            date('Y_m_d_H_i_s', strtotime('now')),
            $format
        );

        return $this->getResponse(
            $format,
            $filename,
            $source
        );
    }

    private function getResponse($format, $filename, SourceIteratorInterface $source)
    {
        switch ($format) {
            case 'xls':
                $writer = new XlsWriter('php://output');
                $contentType = 'application/vnd.ms-excel';

                break;
            case 'xml':
                $writer = new XmlWriter('php://output');
                $contentType = 'text/xml';

                break;
            case 'json':
                $writer = new JsonWriter('php://output');
                $contentType = 'application/json';

                break;
            case 'csv':
                $writer = new CsvWriter('php://output', ',', '"', '\\', true, true);
                $contentType = 'text/csv';

                break;
            default:
                throw new \RuntimeException('Invalid format');
        }

        $callback = static function () use ($source, $writer) {
            $handler = Handler::create($source, $writer);
            $handler->export();
        };

        return new StreamedResponse($callback, 200, [
            'Content-Type' => $contentType,
            'Content-Disposition' => sprintf('attachment; filename="%s"', $filename),
        ]);
    }
}
