<?php

namespace AppBundle\Controller\Admin;

use AppBundle\Entity\OperationPEE;
use AppBundle\Entity\SMS;
use AppBundle\Entity\SMSCampaignPEE;
use AppBundle\Entity\SMSModel;
use AppBundle\Form\Type\SMSCampaignPEEType;
use AppBundle\Form\Type\SMSModelType;
use AppBundle\Helper\SMSHelper;
use AppBundle\SMS\SMSSender;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Translation\TranslatorInterface;

class SMSController extends Controller
{
    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * @var SessionInterface
     */
    private $session;

    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @var SMSSender
     */
    private $sender;
    

    public function __construct(EntityManagerInterface $em, SessionInterface $session, TranslatorInterface $translator, SMSSender $sender)
    {
        $this->em = $em;
        $this->session = $session;
        $this->translator = $translator;
        $this->sender = $sender;
    }
    


    /**
     * Formulaire d'envoi des sms
     *
     * @Route(
     *      "/sms/campaign/add",
     *      name = "admin_sms_campaign_pee_add"
     * )
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function smsOperationPeeAction(Request $request)
    {
        $ope_id = $request->get('ope');

        $ope = $this->em->getRepository('AppBundle:OperationPEE')->findOneById($ope_id);

        // Formulaire 
        $form = $this->createForm(SMSCampaignPEEType::class, array('ope' => $ope) );

        // Check recipients list by default
        if (!$form->isSubmitted()) {
            if (isset($form->get('recipients')->getConfig()->getAttributes()['choice_list'])) {
                $recipients_list = $form->get('recipients')->getConfig()->getAttributes()['choice_list']->getValues();

                foreach ($recipients_list as &$recipient_id) {
                    $demandepee = $this->em->getRepository('AppBundle:DemandePEE')->findOneById($recipient_id);
                    $recipient_id = $demandepee;
                }
                $form->get('recipients')->setData($recipients_list);
                unset($recipients_list, $demandepee, $recipient_id);
            }
        }

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            SMSHelper::initSender($this->sender);
            
            // Create Campaign
            $campaign = SMSHelper::initCampaignPEE($form->getData());

            $this->em->persist($campaign);
            $this->em->flush();

            // Prepare SMS
            SMSHelper::prepareSMSList($form->getData());
            $campaign = SMSHelper::getCampaign();
            $this->em->persist($campaign);
            $this->em->flush();
            
            // Send SMS
            SMSHelper::sendSMSList();
            
            $campaign = SMSHelper::getCampaign();
            $this->em->persist($campaign);
            $this->em->flush();

            $successes = $this->sender->getSuccesses();
            $errors = $this->sender->getErrors();

            if (count($successes) > 0) {
                $creditUsed = $campaign->getCreditUsed();
                $smsSended = $campaign->getNbSMSSended();
                $recipients = [];
                $remaining_credit = 10000;

                foreach ($successes as $suc) {
                    if (isset($suc['recipient'])) {
                        $recipients[] = $suc['recipient'];
                    }
                    elseif (isset($suc['data']['to'])) {
                        $recipients[] = $suc['data']['to'];
                    } 

                    if (isset($suc['data']['remaining_credit'])) {
                        if ($suc['data']['remaining_credit'] < $remaining_credit) {
                            $remaining_credit = (float) $suc['data']['remaining_credit'] / 100;
                        }
                    }
                    
                }
                if($remaining_credit == 10000) {
                    $remaining_credit = "Inconnu";
                }

                $msg = $this->translator->trans(
                    "notice.sms.operationpee.success",
                    ['%count%' => $smsSended, '%credit_used%' => $creditUsed, '%remaining_credit%' => $remaining_credit],
                    'notice'
                );

                $this->addFlash('success', $msg);
            }
            
            if (count($errors) > 0) {
                $countErrors = count($errors);
                $recipients = [];

                foreach ($errors as $err) {
                    if (isset($err['recipient'])) {
                        $recipients[] = $err['recipient'];
                    }
                    elseif (isset($err['data']['to'])) {
                        $recipients[] = $err['data']['to'];
                    } 
                }

                $msg = $this->translator->transchoice(
                    "notice.sms.operationpee.failure",
                    $countErrors,
                    ['%to%' => implode(', ', $recipients)],
                    'notice'
                );

                $this->addFlash('error', $msg);
            }

            return $this->redirectToRoute('admin_sms_campaign_pee_add', array(
                'ope' => $ope_id,
            ));
        }

        return $this->render('Admin/SMS/campaign/add.html.twig', array(
            'form' => $form->createView(),
            'ope' => $ope_id,
        ));
    }

    /**
     * Ajax : Replace Operation keywords by true content
     *
     * @Route(
     *      "/sms/campaign/ajax-update-content/{id}",
     *      name = "admin_sms_campaign_pee_update_content"
     * )
     * @param Request $request
     * @param OperationPEE $ope
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function ajaxSmsOperationPeeReplaceKeywordsAction(Request $request, OperationPEE $ope)
    {
        $content = $request->get('content');

        $new_content = SMSHelper::prepareCampaignPEEContent($content, $ope);

        return new JsonResponse(array('result' => true, 'content' => $new_content));
    }
    
    /**
     * List all models
     *
     * @Route(
     *      "/sms/model/list/{page}",
     *      requirements = {"page": "\d+"},
     *      name = "admin_sms_model_index"
     * )
     *
     * @param Request $request
     * @param int $page
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function smsModelListAction(Request $request, int $page = 1)
    {
        $resultsMaxPerPage = $this->getParameter('results.admin.max_per_page');
        $firstresult = ($page - 1) * $resultsMaxPerPage;

        $search_title = $request->get('title');

        // Mise à jour de la session avec les nouvelles valeurs
        $this->session->set($request->get('_route'), array(
            'page' => $page,
        ));

        $qb = $this->em->createQueryBuilder()
            ->select('m')
            ->from(SMSModel::class, 'm')
            ->orderBy('m.id', 'asc')
            ->setFirstResult($firstresult)
            ->setMaxResults($resultsMaxPerPage)
        ;
        if ($search_title) {
            $qb
                ->andWhere($qb->expr()->like(
                    $qb->expr()->upper('m.title'),
                    $qb->expr()->upper(':m_title')
                ))
                ->setParameter('m_title', '%'.$search_title.'%')
            ;
        }

        $models = new Paginator($qb->getQuery());

        $nbPage = ceil(count($models) / $resultsMaxPerPage);

        // Constructeur pagination
        // $pagination = array();
        // for ($i = 1 ; $i < $nbPage + 1 ; $i++) {
        //     array_push($pagination, $i);
        // }
        
        return $this->render('Admin/SMS/model/index.html.twig', array(
            'search_title' => $search_title,
            'models' => $models,
            'pagination' => $nbPage,
            'pageactuelle' => $page,
        ));
    }
    
    /**
     * @Route(
     *      "/sms/model/add",
     *      name = "admin_sms_model_add"
     * )
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function smsModelAddAction(Request $request)
    {
        $model = new SMSModel;

        // Formulaire 
        $form = $this->createForm(SMSModelType::class, $model);
        $form->handleRequest($request);

        
        if ($form->isSubmitted() && $form->isValid()) {
            // Update model
            $this->em->persist($model);

            $this->em->flush();

            $this->addFlash('success', 'Modèle SMS ajouté');

            return $this->redirectToRoute('admin_sms_model_edit', array(
                'id' => $model->getId(),
            ));
        }

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

    /**
     *
     * @Route(
     *      "/sms/model/edit/{id}",
     *      name = "admin_sms_model_edit"
     * )
     *
     * @param Request $request
     * @param SMSModel $content
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function smsModelEditAction(Request $request, SMSModel $model)
    {
        $form = $this->createForm(SMSModelType::class, $model);
        $form->handleRequest($request);
        
        if ($form->isSubmitted() && $form->isValid()) {
            // Update model
            $this->em->persist($model);

            $this->em->flush();

            $this->addFlash('success', 'Modèle SMS modifié');

            return $this->redirectToRoute('admin_sms_model_edit', array(
                'id' => $model->getId(),
            ));
        }

        return $this->render('Admin/SMS/model/form.html.twig', array(
            'form' => $form->createView()
        ));
    }
    
    /**
     *
     * @Route(
     *      "/sms/model/delete/{id}",
     *      name = "admin_sms_model_delete",
     *  )
     * @param Request $request
     * @param SMSModel $content
     * @return Response
     */
    public function ajaxDeleteAction(Request $request, SMSModel $model)
    {
        $this->em->remove($model);
        $this->em->flush();

        $this->addFlash('success', ' supprimé');

        return new Response();
    }
    
    /**
     *
     * @Route(
     *      "/sms/model/get-content/",
     *      name = "admin_sms_model_get_content"
     * )
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function ajaxGetSMSModelAction(Request $request)
    {
        $id = $request->get('id');
        
        $model = $this->em->getRepository(SMSModel::class)->findOneById($id);

        return new JsonResponse(array('result' => true, 'content' => $model->getContent()));
    }
}