<?php

namespace App\Controller;

use App\Entity\WidgetForm;
use App\Entity\WidgetFormInput;
use App\Form\WidgetFormType;
use App\Repository\WidgetFormRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Form\WidgetFormInputType;
use Symfony\Component\HttpClient\CachingHttpClient;
use Symfony\Component\HttpKernel\HttpCache\Store;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use App\Bundle\Calltouch\Request as CalltouchRequest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

/**
 * @Route("/widget/form")
 */
class WidgetFormController extends AbstractController
{
    private $client;

    public function __construct(HttpClientInterface $client, string $rootPath)
    {
        $store = new Store($rootPath . '/var/HttpClient');
        $this->client = new CachingHttpClient($client, $store);
    }

    /**
     * @IsGranted("ROLE_ADMIN")
     * @Route("/", name="widget_form_index", methods={"GET"})
     */
    public function index(WidgetFormRepository $widgetFormRepository): Response
    {
        return $this->render('widget_form/index.html.twig', [
            'widget_forms' => $widgetFormRepository->findAll(),
        ]);
    }

    /**
     * @IsGranted("ROLE_ADMIN")
     * @Route("/new", name="widget_form_new", methods={"GET","POST"})
     */
    public function new(Request $request): Response
    {
        $widgetForm = new WidgetForm();
        $form = $this->createForm(WidgetFormType::class, $widgetForm);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($widgetForm);
            $entityManager->flush();

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

        return $this->render('widget_form/new.html.twig', [
            'widget_form' => $widgetForm,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @IsGranted("ROLE_ADMIN")
     * @Route("/{id}/editor", name="widget_form_editor", methods={"GET"})
     */
    public function editor(WidgetForm $widgetForm, Request $request, $id): Response
    {
        $widgetFormInput = new WidgetFormInput();
        $form = $this->createForm(WidgetFormInputType::class, $widgetFormInput, [
            'action' => $this->generateUrl('widget_form_input_new', ['id' => $widgetForm->getId()]),
            'method' => 'POST',
        ]);

        $form->handleRequest($request);

        return $this->render('widget_form/editor.html.twig', [
            'form_input' => $widgetForm->getWidgetFormInputs(),
            'widget_form' => $widgetForm,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="widget_form_show", methods={"GET", "POST"})
     */
    public function show(Request $request, WidgetForm $widgetForm, $id): Response
    {
        $fields = [];

        switch (base64_decode($request->query->get('ref') ?? $request->request->get('ref'))) {
            case 'https://volgograd.sovamed.ru':
                $regionId = 92;
                $fields['UF_CRM_1539951158'] = 96;
                // Волгоград
            break;

            case 'https://voronezh.sovamed.ru':
                $regionId = 93;
                $fields['UF_CRM_1539951158'] = 98;
                // Воронеж
            break;

            case 'https://wmtmed.ru':
                $regionId = 94;
                $fields['UF_CRM_1539951158'] = 3018;
                // Краснодар
            break;

            case 'https://sovenok.sovamed.ru':
                $regionId = 95;
                $fields['UF_CRM_1539951158'] = 94;
                // Совенок
            break;

            case 'https://comfort.sovamed.ru':
                $regionId = 96;
                $fields['UF_CRM_1539951158'] = 94;
                // Комфорт
            break;

            default:
                $regionId = 91;
                $fields['UF_CRM_1539951158'] = 94;
                // Саратов
            break;
        }

        if ($request->getMethod() == 'POST' && !empty($request->request->get('fields'))) {
            $fields = array_merge($request->request->get('fields'), $fields);
            $fields['ASSIGNED_BY_ID'] = 506;

            if (!empty($fields['OPPORTUNITY']))
                $fields['OPPORTUNITY'] = preg_replace('/[^0-9]/', '', $fields['OPPORTUNITY']);

            $this->client->request('POST', $_ENV['BITRIX24_URL'], [
                'verify_peer' => false,
                'verify_host' => false,
                'base_uri' => 'https://sovamed.bitrix24.ru',
                'headers' => [
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json',
                    'User-Agent' => 'sovamed_bot',
                ], 
                'query' => ['fields' => $fields]
            ]);
            
            $data = [
                'requestNumber' => \md5(\time()),
                'requestUrl' => $request->request->get('requestUrl'),
                'requestDate' => \date('d-m-Y H:i:s'),
                'subject' => $fields['TITLE'],
                'sessionId' => $request->query->get('sessionId') ?? $request->request->get('sessionId'),
                'phoneNumber' => $fields['PHONE'][0]['VALUE'],
                'fio' => $fields['NAME'],
                'tag' => str_replace(' ', '_', $fields['TITLE']),
            ];

            if ($request->request->get('utm_source') 
                && $request->request->get('utm_medium') 
                && $request->request->get('utm_campaign')
                && $request->request->get('utm_content')
                && $request->request->get('utm_term')) {
                $data['customSources'] = [
                    "source" => $request->request->get('utm_source'),
                    "medium" => $request->request->get('utm_medium'),
                    "campaign" => $request->request->get('utm_campaign'),
                    "content" => $request->request->get('utm_content'),
                    "term" => $request->request->get('utm_term')
                ];
            }

            $calltouch = new CalltouchRequest();
            $calltouch->changeRegion($regionId);
            $calltouch = $calltouch->create($data);   

            return $this->render('widget_form/show.html.twig', [
                'widget_form' => $widgetForm,
                'renderForm' => false
            ]);
        }

        return $this->render('widget_form/show.html.twig', [
            'regionId' => $regionId,
            'widget_form' => $widgetForm,
            'renderForm' => true 
        ]);
    }

    /**
     * @IsGranted("ROLE_ADMIN")
     * @Route("/{id}/edit", name="widget_form_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, WidgetForm $widgetForm): Response
    {
        $form = $this->createForm(WidgetFormType::class, $widgetForm);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();

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

        return $this->render('widget_form/edit.html.twig', [
            'widget_form' => $widgetForm,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @IsGranted("ROLE_ADMIN")
     * @Route("/{id}/delete", name="widget_form_delete", methods={"POST"})
     */
    public function delete(Request $request, WidgetForm $widgetForm): Response
    {
        if ($this->isCsrfTokenValid('delete'.$widgetForm->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($widgetForm);
            $entityManager->flush();
        }

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