<?php

namespace App\Controller;

use App\Entity\Filial;
use App\Repository\FilialRepository;
use App\Entity\AlertSms;
use App\Repository\SpecialistViewRepository as SpecialistRepository;
use App\Repository\ReviewSourceRepository;
use App\Repository\LocationViewRepository as LocationRepository;
use App\Repository\RecordRepository;
use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Form\ReferenceType;
use App\Bundle\Infoclinica\Region;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use App\Bundle\Utils\Logger;
use App\Bundle\Sms\Manager as SmsManager;
use Symfony\Component\HttpFoundation\Request;
use App\Service\SpecialistService;

/**
 * @Route("/widget")
 */
class WidgetController extends AbstractController
{
    /**
     * @Route("/review_source/{cityId}", name="widget_review_source", methods={"GET"})
     */
    public function reviewSource(ReviewSourceRepository $reviewSourceRepository, $cityId): Response
    {
        $reviewSources = [];

        foreach ($reviewSourceRepository->findByCity($cityId) as $key => $reviewSource) {
            $reviewSources[$key] = $reviewSource;
            $reviewSources[$key]['isFloat'] = true;
            $f = (float) $reviewSource['rating_total'];

            if (strpos($reviewSource['rating_total'], '.')  === false) {
                $reviewSources[$key]['isFloat'] = false;
            }
        }

        return $this->render('widget/review_source.html.twig', [
            'reviewSources' =>  $reviewSources,
        ]);
    }

    /**
     * @Route("/reference", name="widget_reference")
     */
    public function reference(Request $request): Response
    {
        $ref = $request->query->get('ref', '');
        $regionId = match (base64_decode($ref, strict: true)) {
            'https://volgograd.sovamed.ru' => 92,
            'https://voronezh.sovamed.ru' => 93,
            'https://wmtmed.ru' => 94,
            default => 91,
        };

        $isAuthorized = $this->isGranted('ROLE_USER');

        $referenceForm = $this->createForm(ReferenceType::class, new User, [
            'method' => 'GET',
            'isAuthorized' => $isAuthorized,
        ]);
        
        return $this->render('widget/reference.html.twig', [
            'regionId' => $regionId,
            'referenceForm' => $referenceForm->createView()
        ]);
    }

    /**
     * @Route("/check/{hash}/{id}", name="widget_check", methods={"GET"})
     */
    public function check(
        RecordRepository $recordRepository, 
        FilialRepository $filialRepository,
        HttpClientInterface $client,
        SpecialistService $specialistService,
        $hash,
        $id
    ): Response {
        $record = $recordRepository->findOneBy(['hash' => $hash, 'id' => $id]);

        if ($record) {
            $reserve = $record->getReserve();
            $reserve['date'] = \date('d-m-Y', strtotime($reserve['date']));
            
            $sms = new SmsManager($client);
            $msg = 'Ждем Вас: ';
            
            $filial = $filialRepository->findOneBy(['fid' => $reserve['filial']]);

            if ($filial) $msg .= $filial->getName() . ' ';
            
            $msg .= $reserve['date'] . ' в '. $reserve['st'];

            if (Region::getTemplite() == 'base') {
                if (!$record->getAlertSms()) {
                    $response = $sms->sendSmsSova($record->getPhone(), $msg);

                    $alertSms = new AlertSms();
                    $alertSms
                        ->setDateCreate(new \DateTime())
                        ->setResponse(json_encode($response, JSON_UNESCAPED_UNICODE))
                        ->setRecord($record);
                    
                    $entityManager = $this->getDoctrine()->getManager();
                    $entityManager->persist($alertSms);
                    $entityManager->flush();
                }

                $html = '<img src="' 
                    . $this->getParameter('public_directory') 
                    . '/images/logo-sova.jpg" alt="logo" width="206"><hr>';
            } else {
                if (!$record->getAlertSms()) {
                    $response = $sms->sendSmsWmt($record->getPhone(), $msg);
                    
                    $alertSms = new AlertSms();
                    $alertSms
                        ->setDateCreate(new \DateTime())
                        ->setResponse(json_encode($response, JSON_UNESCAPED_UNICODE))
                        ->setRecord($record);
                    
                    $entityManager = $this->getDoctrine()->getManager();
                    $entityManager->persist($alertSms);
                    $entityManager->flush();    
                }

                $html = '<img src="' 
                    . $this->getParameter('public_directory') 
                    . '/img/logo_wmt/logo-pdf.jpg" alt="logo" width="256"><hr>';
            }


            $specialist = $specialistService->show(['dcode' => $reserve['dcode']]);
            
            if ($specialist) {
                $html .= '<h2>' . $specialist->getName() . '</h2>';
            }

            $html .= '<p><b>Филиал:</b> ' . $filial->getName(). '</p>';
            $html .= '<p><b>Дата приема:</b> '. $reserve['date'] . ' c '. $reserve['st']. ' по ' . $reserve['en'] .'</p>';
            $html .= '<p><i>На Ваш номер отправлено смс с информацией о приеме</i></p>';
            
            $mpdf = new \Mpdf\Mpdf();
            $mpdf->WriteHTML($html);
            $mpdf->Output();
        }

        throw $this->createNotFoundException('The event does not exist');
    }
}
