<?php

namespace App\Controller;

use App\Bundle\Infoclinica\Region;
use App\Entity\Filial;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use App\Repository\SpecialistRepository;
use App\Repository\DepartmentRepository;
use App\Repository\PriceDepartmentRepository;
use App\Repository\PriceListRepository;
use App\Entity\PriceList;
use Knp\Component\Pager\PaginatorInterface;
use App\Entity\PriceDepartment;
use App\Form\PriceListFormType;
use App\Form\PriceListAdminFormType;
use App\Form\PriceListUpdateAdminFormType;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use App\Service\PriceListService;
use App\Service\SpecialistService;

/**
 * @Route("/")
 */
class DefaultController extends AbstractController
{
    private $client;

    public function __construct(HttpClientInterface $client, KernelInterface $kernel)
    {
        $this->client = $client;
        $this->kernel = $kernel;
    }

    /**
     * @IsGranted("ROLE_USER")
     * @Route("/", name="default_index")
     */
    public function index(): Response
    {
        return $this->render('base/index.html.twig', [
            'template' => Region::getTemplite(),
            'alias' => '',
            'title' => 'Личный кабинет'
        ]);
    }
    
    /**
     * @Route("/doctor-your-home", name="default_doc_your_home")
     */
    public function doctorYourHome(): Response
    {
        return $this->render('base/doc_your_home.html.twig', [
            'template' => Region::getTemplite(),
            'title' => 'Вызов врача на дом'
        ]);
    }


    /**
     * @Route("/stoimost-uslug", name="default_price")
     */
    public function price(PriceListService $priceListService, PaginatorInterface $paginator, Request $request): Response
    {
        $priceList = new PriceList();
        $searchForm = $this->createForm(PriceListFormType::class, $priceList, [
            'action' => $this->generateUrl('default_price'),
            'method' => 'GET',
        ]);

        $searchForm->handleRequest($request);

        $filters = $request->query->get('price_list_form', []);
        $priceListQuery = $priceListService->getFilteredPriceListQuery($filters);
        
        $pagination = $paginator->paginate(
            $priceListQuery->getQuery(),
            $request->query->getInt('page', 1),
            50
        );

        return $this->render('base/price.html.twig', [
            'title' => 'Стоимость услуг',
            'template' => Region::getTemplite(),
            'pagination' => $pagination,
            'searchForm' => $searchForm->createView()
        ]);
    }

    /**
     * @IsGranted("ROLE_ADMIN")
     * @Route("/update/price-list", name="default_update_price_list", methods={"POST"})
     */
    public function uploadPrice(Request $request): Response 
    {
        $application = new Application($this->kernel);
        $application->setAutoExit(false);

        $input = new ArrayInput([
            'command' => 'app:UploadPice',
            'did' => $request->request->get('groupId'),
            '--nosleep' => true
        ]);

        // Вы можете использовать NullOutput(), если вам не нужен вывод
        $output = new BufferedOutput();
        $application->run($input, $output);

        return $this->json(
            (strpos($output->fetch(), '[OK] successful') === false)? ['status' => false]: ['status' => true]
        );
    }

    /**
     * @IsGranted("ROLE_ADMIN")
     * @Route("/price-list", name="default_price_list")
     */
    public function priceList(
        PriceListService $priceListService, 
        PriceListRepository $priceListRepository, 
        PaginatorInterface $paginator, 
        Request $request
    ): Response {   
        $priceList = new PriceList();
        $searchForm = $this->createForm(PriceListAdminFormType::class, $priceList, [
            'action' => $this->generateUrl('default_price_list'),
            'method' => 'GET',
        ]);
        $searchForm->handleRequest($request);
        
        $params = $request->query->get('default_price_list',[]);

        $priceListQuery = $priceListService->getPriceListQuery($params);
        $pagination = $paginator->paginate(
            $priceListQuery->getQuery(),
            $request->query->getInt('page', 1), 
            50
        );

        return $this->render('base/price_list.html.twig', [
            'priceList' => $priceList,
            'dateActive' => (new \DateTime())->modify('-2 day')->format('Y-m-d 00:00:00'),
            'title' => 'Сравнение цен',
            'template' => Region::getTemplite(),
            'pagination' => $pagination,
            'searchForm' => $searchForm->createView()
        ]);
    }

    private function getPricelist($depnum)
    {
        $response = [];
        $flag = true;
        $firstrow = 1;
        $lastrow = 500;
        
        while ($flag) {
            $result = $this->client->request('GET', 'pricelist/list', [
                'verify_peer' => false,
                'verify_host' => false,
                'base_uri' => 'https://widget.sovamed.ru',
                'headers' => [
                    'Content-Type' => 'application/json',
                    'User-Agent' => 'sovamed_bot'
                ],
                'query' => [
                    'depnum' => $depnum,
                    'firstrow' => $firstrow,
                    'lastrow' => $lastrow
                ],
            ]);

            $firstrow = $lastrow + 1; 
            $lastrow = $lastrow + 500; 
            $result = $result->toArray();
            
            if (empty($result['data'])) {
                $flag = false;
            } else {
                $response[] = $result['data'];
            }
        }

        return $response;
    }

    /**
     * @Route("/info", name="default_info")
     */
    public function info(): Response
    {  
        return $this->render('base/doc.html.twig', [
            'template' => Region::getTemplite(),
            'title' => 'Информация'
        ]);
    }

    /**
     * @Route("/help", name="default_help")
     */
    public function help(Request $request): Response
    {
        if ($request->getMethod() == 'POST') {
            $params = $request->request->get('help');
            $to = 'i.alexandrov@sova.clinic';
            $subject = $params['team'];
            $headers = 'From: ' . $params['email'] . "\r\n" .
                'Reply-To: ' . $params['email'] . "\r\n" .
                'X-Mailer: PHP/' . phpversion();
            
            $message = 'ФИО:' . $params['fio'] ."\r\n";
            $message .= 'Телефон:' . $params['phone'] ."\r\n";
            $message .= 'Вопрос:' . $params['question'] ."\r\n";

            $message = wordwrap($message, 70, "\r\n");

            if (mail($to, $subject, $message, $headers)) {
                $this->addFlash(
                    'success',
                    'Спасибо, мы получили Ваше сообщение.'
                );
            } else {
                $this->addFlash(
                    'notice',
                    'Cервис временно не доступен!'
                );
            }
        }

        return $this->render('base/help.html.twig', [
            'template' => Region::getTemplite(),
            'title' => 'Помощь'
        ]);
    }
}
