<?php

namespace AppBundle\Controller\Module;

use AppBundle\Controller\ModuleController;
use AppBundle\Entity\DemandePEE;
use AppBundle\Entity\Module;
use AppBundle\Entity\OperationPEE;
use AppBundle\Entity\OperationPEECategory;
use AppBundle\Entity\User;
use AppBundle\Enum\DemandePEEState;
use AppBundle\Helper\OperationHelper;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class MapPeeController extends ModuleController
{
    /**
     * @param Int $moduleId Défini le module à afficher
     * @param string $force_layout Définit le type de rendu Twig souhaité
     * @param Int $menuId Défini le menu associé, la page actuelle qui demande l'affichage
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function renderModule(Int $moduleId, string $force_layout = null, Int $menuId = null)
    {
        $module = $this->em->getRepository(Module::class)->findOneBy([
            'isActive' => true, 
            'id' => $moduleId
        ]);
        
        if (empty($module)) {
            return new Response('');
        }

        //Force layout
        if (!empty($force_layout)) {
            $module->setLayout($force_layout);
        }
        
        $module->setFormClass($module->getType());
        $layout = $module->getLayoutPath();

        //Check if layout is correct
        if (!empty($force_layout) && strpos($layout, $force_layout) === false) {
            return new Response('');
        }

        $user = $this->getUser();
        
        $request = Request::createFromGlobals();
        parse_str($request->server->get('QUERY_STRING'), $url_params);

        $categories = $this->em->getRepository(OperationPEECategory::class)->findBy(['isActive' => true], array('name' => 'ASC'));
        
        return $this->render($layout , array(
            'module' => $module, 
            'search_zicode' => $url_params['zipCode'] ?? null,
            'search_latitude' => $url_params['search_latitude'] ?? null,
            'search_longitude' => $url_params['search_longitude'] ?? null,
            'search_category' => $url_params['category'] ?? null,
            'search_dateVisite' => $url_params['dateVisite'] ?? null,
            'categories' => $categories,
        ));
    }    


    /**
     * Affiche les pages possédant un template
     *
     * @Route(
     *      "/module-mappee/{id}/get-operations",
     *      name = "module_mappee_get_operations"
     * )
     *
     * @param Request $Request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function getOperationsAction(Request $request, Module $module)
    {  
        $user = $this->getUser();
        OperationHelper::setUser($user);
        
        $search_zipcode = (int) $request->get('zipCode') ?? null;
        $search_latitude = (float) $request->get('search_latitude') ?? null;
        $search_longitude = (float) $request->get('search_longitude') ?? null;
        $search_category = (int) $request->get('category') ?? null;
        $search_datevisite = $request->get('dateVisite') ?? null;

        $filters = array();

        //if (!empty($search_zipcode)) { $filters['zipCode'] = (int) $search_zipcode; }
        if (!empty($search_category)) { $filters['category'] = (int) $search_category; }
        if (!empty($search_datevisite)) { 
            if (preg_match("#([0-9]{2})\/([0-9]{2})\/([0-9]{4})#", $search_datevisite, $matches)) {
                list($date, $day, $month, $year) = $matches;
                $search_datevisite = $year . '-' . $month . '-' . $day;
            }

            $filters['dateVisite'] = $search_datevisite; 
        }

        if (!empty($search_latitude) && !empty($search_longitude)) {
            $filters['search_from_origin_position'] = array();
            $filters['search_from_origin_position']['latitude'] = (float) $search_latitude;
            $filters['search_from_origin_position']['longitude'] = (float) $search_longitude;
        }

        // Filter the operations with applications (from the connected user, see findOpenForApplication() above)
        $operations = $this->em->getRepository(OperationPEE::class)->findOpenForApplication($user, $filters);
       
        $fullListOperations = $this->em->getRepository(OperationPEE::class)->findOpenForApplication($user);
        $userOperationsTmp = OperationHelper::filterByUserApplication($fullListOperations);
        $userOperations = $datesTaken = array();
        foreach ($userOperationsTmp as $ope) {
            
            
            $demandepee = $ope['details']->getDemandepee()->first();
           
            if ( $demandepee !== null ) {
                $userOperations[$ope['details']->getId()] = $demandepee;
                if (null !== $ope['details']->getDateVisite()) {
                    $datesTaken[] = $ope['details']->getDateVisite()->format('Ymd');
                }
            }
        }
        
        // Get the number of user applications
        $userOperationsQty = OperationHelper::getUserApplicationQty($fullListOperations);

        $oChecked = $this->session->get('espace_perso_pee_add_operations') ?? [] ;
        $oCerpepChecked = $this->session->get('espace_perso_pee_add_operations_cerpep') ?? [];
        
        return $this->render('Front/Render/Module/MapPee/_operations.html.twig' , array(
            'module' => $module,
            'operations' => $operations,
            'registered' => $userOperations,
            'registeredQty' => $userOperationsQty, // Count user registrations. Limit by user into config.yml file
            'datesTaken' => $datesTaken, 
            'selectedOpe' => $oChecked, 
            'selectedOpeCerpep' => $oCerpepChecked,
            'search_zicode' => !empty($search_zipcode) ? $search_zipcode : null,
            'search_latitude' => !empty($search_latitude) ? $search_latitude : null,
            'search_longitude' => !empty($search_longitude) ? $search_longitude : null,
            'search_category' => !empty($search_category) ? $search_category : null,
            'search_datevisite' => !empty($search_datevisite) ? $search_datevisite : null,
        ));
    }
}
