<?php

namespace App\Controller;

use App\Service\SpecialistService;
use App\Entity\SpecialistView;
use App\Bundle\Infoclinica\Region;
use App\Bundle\Bitrix\Request as Bitrix;
use App\Form\SpecialistSearchType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

class SpecialistController extends AbstractController
{
    /**
     * @Route("/filter", name="specialist_filter", methods={"GET"})
     */
    public function filter(Request $request): Response
    {
        $regionId = $request->cookies->getInt('region');
        $regionId = ($regionId > 0) ? $regionId : null;
        
        // Получаем значение kinder из запроса для фильтрации специализаций
        $kinder = $request->query->get('specialist_search')['kinder'] ?? null;
        $kinder = ($kinder == 1) ? 1 : null;
        
        $searchForm = $this->createForm(SpecialistSearchType::class, new SpecialistView(), [
            'action' => $this->generateUrl('specialist_index'),
            'method' => 'GET',
            'regionId' => $regionId,
            'kinder' => $kinder,
        ]);
        
        $searchForm->handleRequest($request);

        return $this->render('specialist/_search_form.html.twig', [
            'searchForm' => $searchForm->createView()
        ]);
    }

    /**
     * @Route("/specialists/{alias?}", name="specialist_index", methods={"GET"})
     */
    public function index(
        SpecialistService $specialistService, 
        Request $request,
        string $alias = null 
    ): Response {
        $regionId = $request->cookies->getInt('region');
        $regionId = ($regionId > 0) ? $regionId : null;
        
        // Получаем значение kinder из запроса для фильтрации специализаций
        $kinder = $request->query->get('specialist_search')['kinder'] ?? null;
        $kinder = ($kinder == 1) ? 1 : null;
        
        $searchForm = $this->createForm(SpecialistSearchType::class, new SpecialistView(), [
            'action' => $this->generateUrl('specialist_index', ['alias' => $alias]),
            'method' => 'GET',
            'regionId' => $regionId,
            'kinder' => $kinder,
        ]);

        $searchForm->handleRequest($request);

        $page = $request->query->getInt('page', 1);
        
        $filters = $request->query->get('specialist_search', ['onlineMode' => 0]);
        $filters['depAlias'] = $alias;
        
        if ($regionId > 0) {
            $filters['regionId'] = $regionId;
        }

        $pagination = $specialistService->listPaginated($filters, $page, 10);
        $view = 'specialist/index.html.twig';

        if (Region::getTemplite() == 'krasnodar_base') {
            $view = 'specialist/krasnodar_index.html.twig';
        }

        if (! empty($request->query->get('specialist_search')['current_date'])) {
            $currentDate = $request->query->get('specialist_search')['current_date'];
            $dates = explode('-', $currentDate);
            $startInterval = $dates[0];
            $endInterval = $dates[1];
        } else {
            $startInterval = date("Y-m-d");
            $endInterval = date("Y-m-d", strtotime('+7 day'));
        }

        return $this->render($view, [
            'title' => 'Врачи',
            'alias' => $alias,
            'template' => Region::getTemplite(),
            'pagination' => $pagination,
            'searchForm' => $searchForm->createView(),
            'st' => $startInterval,
            'en' => $endInterval
        ]);
    }

    /**
     * @IsGranted("ROLE_USER")
     * @Route("/online-specialists", name="specialist_online_index", methods={"GET"})
     */
    public function onlineIndex(
SpecialistService $specialistService, 
        Request $request
    ): Response {
        $regionId = $request->cookies->getInt('region');
        $regionId = ($regionId > 0) ? $regionId : null;
        
        // Получаем значение kinder из запроса для фильтрации специализаций
        $kinder = $request->query->get('specialist_search')['kinder'] ?? null;
        $kinder = ($kinder == 1) ? 1 : null;
        
        $searchForm = $this->createForm(SpecialistSearchType::class, new SpecialistView(), [
            'action' => $this->generateUrl('specialist_index'),
            'method' => 'GET',
            'regionId' => $regionId,
            'kinder' => $kinder,
        ]);

        $searchForm->handleRequest($request);

        $filters = $request->query->get('specialist_search', ['onlineMode' => 1]);
        
        if ($regionId > 0) {
            $filters['regionId'] = $regionId;
        }
        
        $page = $request->query->getInt('page', 1);

        $pagination = $specialistService->listPaginated($filters, $page, 10);

        $view = 'specialist/index.html.twig';

        if (Region::getTemplite() == 'krasnodar_base') {
            $view = 'specialist/krasnodar_index.html.twig';
        }

        if (! empty($request->query->get('specialist_search')['current_date'])) {
            $currentDate = $request->query->get('specialist_search')['current_date'];
            $dates = explode('-', $currentDate);
            $startInterval = $dates[0];
            $endInterval = $dates[1];
        } else {
            $startInterval = date("Y-m-d");
            $endInterval = date("Y-m-d", strtotime('+7 day'));
        }

        return $this->render($view, [
            'title' => 'Онлайн консультация',
            'template' => Region::getTemplite(),
            'pagination' => $pagination,
            'searchForm' => $searchForm->createView(),
            'st' => $startInterval,
            'en' => $endInterval
        ]);
    }

    /**
     * @Route("/specialist/{alias}", name="specialist_show", methods={"GET"})
     */
    public function show(
        SpecialistService $specialistService,
        Request $request,
        string $alias
    ): Response {
        $filters = $request->query->get('specialist_search', ['onlineMode' => 0]);
        // $filters['regionId'] = $request->cookies->getInt('region');
        $filters['alias'] = $alias;
        
        $specialist = $specialistService->show($filters);

        if ($specialist) {
            $specialistMoreService = $specialist->getSpecialistMore();

            if ($defaultLocation = $specialistMoreService->defaultLocation()) {
                return $this->render('specialist/show.html.twig', [
                    'title' => 'Врач',
                    'st' => date("Y-m-d"),
                    'en' => date("Y-m-d", strtotime('+7 day')),
                    'template' => Region::getTemplite(),
                    'specialist' => $specialist,
                    'specialistMore' => $specialistMoreService,
                ]);
            }
        }

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

    /**
     * @Route("/favorites", name="default_favorites")
     */
    public function favorites(SpecialistService $specialistService, Request $request): Response
    {
        $page = $request->query->getInt('page', 1);
        $filters['dcode'] = explode(',', $request->query->get('q'));

        $pagination = $specialistService->listPaginated($filters, $page, 10);

        return $this->render('base/favorites.html.twig', [
            'st' => date("Y-m-d"),
            'en' => date("Y-m-d", strtotime('+7 day')),
            'pagination' => $pagination,
            'template' => Region::getTemplite(),
            'title' => 'Избранное'
        ]);
    }
}
