<?php
declare(strict_types=1);
namespace App\Controller;
use App\Entity\Document;
use App\Entity\FicheAction;
use App\Entity\Keyword;
use App\Entity\PartnerAction;
use App\Form\FicheActionFilterType;
use Cocur\Slugify\Slugify;
use Doctrine\Persistence\ManagerRegistry;
use Knp\Component\Pager\PaginatorInterface;
use Knp\Snappy\Pdf;
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\Security\Core\Authorization\AuthorizationCheckerInterface;
/**
* FicheAction controller.
*/
#[Route(path: '/fiche-action')]
class FicheActionController extends AbstractController
{
private PaginatorInterface $paginator;
private ManagerRegistry $em;
private Pdf $pdf;
private AuthorizationCheckerInterface $authorizationChecker;
public function __construct(PaginatorInterface $paginator, AuthorizationCheckerInterface $authorizationChecker, ManagerRegistry $em, Pdf $pdf)
{
$this->paginator = $paginator;
$this->authorizationChecker = $authorizationChecker;
$this->em = $em;
$this->pdf = $pdf;
}
/**
* Lists all FicheAction entities.
*/
#[Route(path: '/', name: 'fiche-action', methods: ['GET'])]
public function index(Request $request): Response
{
$filter = $this->filterForm($request);
$filterData = $filter['filterData'];
$filterForm = $filter['filterForm'];
$queryRequest = $request->query;
// gestion ordre affichage
$sort = $queryRequest->get('sort', 'fa.created');
$direction = $queryRequest->get('direction', 'DESC');
// prise en compte du champ de recherche additionnel TermSearch
$filtreActionFilter = $request->query->get('ficheactionfilter');
if (is_array($filtreActionFilter) && array_key_exists('TermSearch', $filtreActionFilter)) {
$filterData['TermSearch'] = $filtreActionFilter['TermSearch'];
}
if ($request->get('formPartneCloud')) {
$filterData['formPartnerCloud'] = 1;
}
$query = $this->em->getRepository(FicheAction::class)->search($filterData, $sort, $direction);
$paginator = $this->paginator;
$pagination = $paginator->paginate(
$query,
$request->query->getInt('page', 1), /* page number */
25/* limit per page */
);
$pagination->setTemplate('Pagination/pagination.html.twig');
return $this->renderForm('FicheAction/index.html.twig', [
'pagination' => $pagination,
'filterForm' => $filterForm,
'direction' => $direction,
]);
}
/**
* update nbviews fields when fiche action is open.
*/
#[Route(path: '/updateNbViews', name: 'updateNbViews', methods: ['POST'])]
public function updateNbViews(Request $request): Response
{
$ficheAction = $this->em->getRepository(FicheAction::class)->find($request->request->get('id'));
if (!$ficheAction) {
throw $this->createNotFoundException('Unable to find FicheAction entity.');
}
$ficheAction->setNbViews($ficheAction->getNbViews() + 1);
$this->em->getManager()->persist($ficheAction);
$this->em->getManager()->flush();
$return = 'nbviews of fiche action '.$ficheAction->getId().' was updated with success';
return new Response($return, Response::HTTP_OK);
}
private function filterForm(Request $request): array
{
$session = $request->getSession();
$filterData = [];
$filterForm = $this->createForm(FicheActionFilterType::class);
if (!$this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$filterForm->remove('applicants');
}
// Reset filter
if ('reset' == $request->get('filter_action')) {
$session->remove('ficheactionfilter');
}
// Filter action
if ('filter' == $request->get('filter_action')) {
if ($request->get('ficheactionfilter')) {
$ficheActionFilter = $request->get('ficheactionfilter');
if (array_key_exists('department', $ficheActionFilter)) {
$filterData['department'] = $ficheActionFilter['department'];
}
if (array_key_exists('financialPartners', $ficheActionFilter)) {
$filterData['financialPartners'] = $ficheActionFilter['financialPartners'];
}
if (array_key_exists('actionPartners', $ficheActionFilter)) {
$filterData['actionPartners'] = $ficheActionFilter['actionPartners'];
}
if ($request->get('formPartnerCloud')) {
$filterData['formPartnerCloud'] = $request->get('formPartnerCloud');
}
}
// Bind values from the request
$filterForm->handleRequest($request);
if ($filterForm->isSubmitted() && $filterForm->isValid()) {
if ($filterForm->has('department') && ($dep = $filterForm->get('department')->getData())) {
$filterData['department'] = $dep->getId();
}
if ($filterForm->has('region') && ($dep = $filterForm->get('region')->getData())) {
$filterData['region'] = $dep->getId();
}
if ($filterForm->has('public') && ($dep = $filterForm->get('public')->getData())) {
$filterData['public'] = $dep->getId();
}
if ($filterForm->has('dimension') && ($dep = $filterForm->get('dimension')->getData())) {
$filterData['dimension'] = $dep->getId();
}
if ($filterForm->has('actionPartners') && ($dep = $filterForm->get('actionPartners')->getData())) {
$ids = $dep->map(fn ($entity) => $entity->getId());
if ((is_countable($ids) ? count($ids) : 0) > 0) {
$filterData['actionPartners'] = $ids->toArray();
}
}
if ($filterForm->has('financialPartners') && ($dep = $filterForm->get('financialPartners')->getData())) {
$ids = $dep->map(fn ($entity) => $entity->getId());
if ((is_countable($ids) ? count($ids) : 0) > 0) {
$filterData['financialPartners'] = $ids->toArray();
}
}
if ($filterForm->has('applicants') && ($dep = $filterForm->get('applicants')->getData())) {
$ids = $dep->map(fn ($entity) => $entity->getId());
if ((is_countable($ids) ? count($ids) : 0) > 0) {
$filterData['applicants'] = $ids->toArray();
}
}
if ($filterForm->has('keywords') && ($dep = $filterForm->get('keywords')->getData())) {
$ids = $dep->map(fn ($entity) => $entity->getId());
if ((is_countable($ids) ? count($ids) : 0) > 0) {
$filterData['keywords'] = $ids->toArray();
}
}
}
}
// dd($filterData);
return [
'filterForm' => $filterForm,
'filterData' => $filterData,
];
}
/**
* Recherche geographique et par mots cles.
*/
#[Route(path: '/recherche-geographique-mot-cle', name: 'fiche-action_geographical_and_tag_search')]
public function geographicalAndTagSearch(): Response
{
$connection = $this->em->getConnection();
// tags
$keywords = $this->em->getRepository(Keyword::class)->findAllUsedKeyword();
// partnerActions
$partnerActions = $this->em->getRepository(PartnerAction::class)->findAllUsedPartnerAction();
$baseFontSize = '0.8';
$maxFontSize = '2.5';
// map
$BaseQuery = 'SELECT * FROM FicheAction a LEFT JOIN Structure s ON a.structure_id = s.id LEFT JOIN Departement d ON s.departement_id=d.id ';
$statement1 = $connection->prepare('SELECT * FROM imap_departements');
$GetImapDepartements = $statement1->execute()->fetchAll();
$map_array = [];
foreach ($GetImapDepartements as $result) {
$statement2 = $connection->prepare($BaseQuery." WHERE d.num='".$result['id']."'");
$Get_All = $statement2->execute()->fetchAll();
$total_resultats = is_countable($Get_All) ? count($Get_All) : 0;
$map_array[$result['id']]['id'] = $result['id'];
$map_array[$result['id']]['departement'] = $result['departement'];
$map_array[$result['id']]['total_resultats'] = $total_resultats;
$map_array[$result['id']]['coords'] = $result['coords'];
}
return $this->render('FicheAction/geographical_and_tag_search.html.twig', [
'results_tags' => $keywords,
'results_partnerActions' => $partnerActions,
'baseFontSize' => $baseFontSize,
'maxFontSize' => $maxFontSize,
'map_array' => $map_array,
]);
}
/**
* Finds and displays a FicheAction entity.
*/
#[Route(path: '/{id}', name: 'fiche-action_show', methods: ['GET'])]
public function show($id): Response
{
$entity = $this->em->getRepository(FicheAction::class)->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find FicheAction entity.');
}
$entity->setNbViews($entity->getNbViews() + 1);
$this->em->getManager()->persist($entity);
$this->em->getManager()->flush();
return $this->render('FicheAction/show.html.twig', [
'entity' => $entity,
]);
}
#[Route(path: '/document/{id}', name: 'get_document', methods: ['GET'])]
public function getDocument($id): Response
{
$document = $this->em->getRepository(Document::class)->find($id);
if (!$document) {
throw $this->createNotFoundException('Unable to find Document.');
}
$fileName = $document->getWebPath();
$response = new Response();
// Set headers
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-type', mime_content_type($fileName));
$response->headers->set('Content-Disposition', 'inline; filename="'.basename($fileName).'";');
$response->headers->set('Content-length', filesize($fileName));
// Send headers before outputting anything
$response->sendHeaders();
$response->setContent(readfile($fileName));
return $response;
}
/**
* Afficher la fiche action pour impression.
*/
#[Route(path: '/{id}/print', name: 'ficheAction_print', methods: ['GET'])]
public function print($id): Response
{
// security
if (!$this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
throw $this->createAccessDeniedException();
}
$entity = $this->em->getRepository(FicheAction::class)->find($id);
return $this->render('FicheAction/print.html.twig', [
'entity' => $entity,
]);
}
/**
* Afficher la fiche Action en PDF.
*/
#[Route(path: '/{id}/printPdf', name: 'ficheAction_printPdf', methods: ['GET'])]
public function printPdf($id): Response
{
// security
if (!$this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
throw $this->createAccessDeniedException();
}
$entity = $this->em->getRepository(FicheAction::class)->find($id);
$slugify = new Slugify();
$ficheAction_slug = $slugify->slugify($entity);
$path = $this->getParameter('kernel.project_dir').'/public/';
$html = $this->renderView('FicheAction/print.html.twig', ['entity' => $entity, 'path' => $path]);
$this->pdf->setTimeout(180);
$this->pdf->setOption('enable-local-file-access', true);
return new Response(
$this->pdf->getOutputFromHtml(
$html,
[
'orientation' => 'Portrait',
'default-header' => false,
'lowquality' => true,
]
),
Response::HTTP_OK,
[
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="fiche_action-'.$ficheAction_slug.'.pdf"',
]
);
}
}