<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Region;
use App\Entity\Pays;
use App\Entity\Departement;
use App\Repository\AdministrateursRepository;
use App\Repository\GroupeRestrictionRepository;
use App\Repository\GroupeRestrictionPageRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Doctrine\ORM\EntityManagerInterface;
use DateTime;
class DepartementController extends AbstractController
{
public function __construct(SessionInterface $session , Container $container , EntityManagerInterface $em )
{
$this->em = $em ;
$this->session = $session ;
}
#[Route('/configuration_departement', name: 'app_departement')]
public function index(Request $request,GroupeRestrictionRepository $groupeRestrictionRepository,
GroupeRestrictionPageRepository $grouprestrictionpageRepository,
AdministrateursRepository $AdministrateursRepository): Response
{
$accessArray=[];
$niveauAcessPages = [];
$groupeRestrictions = [];
if( ($this->session->get('susrD3p9LjjY86') == 'gA64ya3G5N') && ($request->hasSession()) ){
$admin = $this->session->get('supAdT9m2XJzn4');
}else if(($this->session->get('supAdT9m2XJzn4') != null) && ($request->hasSession())){
$admin = $AdministrateursRepository->findOneBy(['email'=>$this->session->get('supAdT9m2XJzn4')['email']]);
$adminId = $admin->getId();
$groupeRestrictions = $groupeRestrictionRepository->findByAdminId($adminId);
$restrictionPages = $grouprestrictionpageRepository->findByRestriction($groupeRestrictions[0]->getId());
$accessArray = $restrictionPages[0]->getAccess();
$niveauAcessPagesCollection = $restrictionPages[0]->getNiveauAcessPages();
$niveauAcessPagesCollection->initialize();
$niveauAcessPages = $niveauAcessPagesCollection->toArray();
}else {
return $this->redirectToRoute('connexion');
}
$pays = $this->em->getRepository(Pays::class)->findAll();
$region = $this->em->getRepository(Region::class)->findAll();
return $this->render('departement/departement.html.twig', [
'admin' => $admin,
'pays' => $pays,
'access' => $accessArray,
'pages' => $niveauAcessPages,
'regions' => $region,
]);
}
/**
* @Route("/serverDepartement", name="serverDepartement", methods={"GET","POST"}, options = {"expose" = true})
*/
public function serverDepartement(Request $request): Response
{
$sql_where = "" ;
if($request->get('search')['value']!=""){
$sql_where .= ' AND ( u.numero LIKE \'%'.$request->get('search')['value'].'%\' )' ;
$sql_where .= ' OR ( u.nom LIKE \'%'.$request->get('search')['value'].'%\' )';
$sql_where .= ' OR ( u.id LIKE \'%'.$request->get('search')['value'].'%\' )';
$sql_where .= ' OR ( u.cp LIKE \'%'.$request->get('search')['value'].'%\' )';
}
$user_array = [] ;
$limit = $request->get('length') ;
$offset = $request->get('start') ;
$array_search = array();
$columns = ['u.id','u.nom','u.numero','u.cp'];
$orders = [] ;
for($i=0 ; $i<count($request->get('order')) ;$i++ ){
$orders[] = $columns[ $request->get('order')[$i]['column'] ].' '.$request->get('order')[$i]['dir'] ;
}
if( count($orders)>0){
$order = " ORDER BY ".implode(' , ',$orders) ;
}
else{
$order = "" ;
}
$total_departement = [];
$total_departement = $this->em->createQuery(
'SELECT u
FROM App\Entity\Departement u
WHERE 1=1 '.$sql_where.'
'
)
->getResult() ;
$I_nbResultatsTotal = count( $total_departement ) ;
$departements = $this->em->createQuery(
'SELECT u
FROM App\Entity\Departement u
WHERE 1=1 '.$sql_where.' '.$order.'
'
)
->setMaxResults($limit)
->setFirstResult($offset)
->getResult() ;
$output = [] ;
$etat = '';
foreach($departements as $departement){
$output[] = [
'id'=>$departement->getId() ,
'numero'=>$departement->getNumero(),
'nom'=>$departement->getNom(),
'cp'=>$departement->getCp(),
'pays'=>$departement->getPays()->getNomFrFr(),
'region' => $departement->getRegion()->getTitre(),
'dateCreation'=> date_format( $departement->getDateCreation() , 'd/m/Y H:i'),
'dateUpdate' => $departement->getDateUpdate() !== null ? date_format($departement->getDateUpdate(), 'd/m/Y H:i') : '--'
];
}
$JSON = json_encode($output);
$JSON = '{"draw": '.$request->get('draw').',"recordsTotal":'.$I_nbResultatsTotal.',"recordsFiltered":'.$I_nbResultatsTotal.',"data":'.$JSON.'}';
$response = new Response($JSON, 200, ['Content-Type' => 'application/json']);
return $response;
}
/**
* @Route("/ajout_departement", name="ajout_departement" , options = {"expose"=true})
*/
public function ajout_departement(Request $request): Response
{
$departement = new Departement();
$departement->setNumero($request->get('numero'));
$departement->setNom($request->get('nom'));
$departement->setCp($request->get('cp'));
$paysId = $request->get('pays');
$pays = $this->em->getRepository(Pays::class)->find($paysId);
$departement->setPays($pays);
$regionId = $request->get('region');
$region = $this->em->getRepository(Region::class)->find($regionId);
$departement->setRegion($region);
$departement->setDateCreation(\DateTime::createFromFormat('Y-m-d H:i:s', date('Y-m-d H:i:s' ) ) );
try {
$this->em->persist($departement);
$this->em->flush();
return new JsonResponse(['status' => 'OK']);
} catch (\Exception $e) {
return new JsonResponse(['status' => 'KOO','message' => $e->getMessage()]);
}
}
/**
* @Route("/modif_departement/{id}", name="modif_departement" , methods={"POST"}, options = {"expose"=true})
*/
public function modif_departement(int $id, Request $request): Response
{
$departement = $this->em->getRepository(Departement::class)->find($id);
if (!$departement) {
return new JsonResponse(['status' => 'KOO', 'message' => 'Region non trouvé !']);
}
$departement->setNumero($request->get('numero_edit'));
$departement->setNom($request->get('nom_edit'));
$departement->setCp($request->get('cp_edit'));
$paysId = $request->get('pays_edit');
$pays = $this->em->getRepository(Pays::class)->find($paysId);
$departement->setPays($pays);
$regionId = $request->get('region_edit');
$region = $this->em->getRepository(Region::class)->find($regionId);
$departement->setRegion($region);
$currentDateTime = new DateTime();
$departement->setDateUpdate($currentDateTime);
try {
$this->em->persist($region);
$this->em->flush();
return new JsonResponse(['status' => 'OK', 'message' => 'Departement mis à jour avec succès !']);
} catch (\Exception $e) {
return new JsonResponse(['status' => 'error', 'message' => 'Erreur lors de la modification du departement : ' . $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
/**
* @Route("/delete_departement/{id}", name="delete_departement" , methods={"DELETE"}, options = {"expose"=true})
*/
public function delete_departement(int $id, Request $request): Response
{
$departement = $this->em->getRepository(Departement::class)->find($id);
if (!$departement) {
return new Response('Departement not found!', Response::HTTP_NOT_FOUND);
};
try {
$this->em->remove($departement);
$this->em->flush();
return new JsonResponse(['status' => 'OK']);
} catch (\Exception $e) {
return new Response('Error deleting departement: ' . $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
/**
* @Route("/get_pays_departements/{idPays}", name="get_pays_departements" , methods={"GET"}, options = {"expose"=true})
*/
public function get_departements_by_paysId( Request $request,$idPays ): Response
{
if (!$idPays) {
$msg = ['msg'=>'KOO'] ;
$JSON = json_encode($msg);
$response = new Response($JSON, 200, ['Content-Type' => 'application/json']);
return $response;
}
$departements = $this->em->getRepository(Departement::class)->findBy(['pays' => $idPays]);
$res =[];
//dd($departements);
foreach ($departements as $departement) {
$res[] = [
'id' => $departement->getId(),
'nom'=>$departement->getNom()
];
}
$JSON = json_encode($res);
$response = new Response($JSON, 200, ['Content-Type' => 'application/json']);
return $response;
}
/**
* @Route("/get_numero_departements/{id}", name="get_numero_departements" , methods={"GET"}, options = {"expose"=true})
*/
public function get_numero_departements(Request $request, $id): Response
{
if (!$id) {
$msg = ['msg' => 'KOO'];
return new JsonResponse($msg, 200);
}
$departement = $this->em->getRepository(Departement::class)->find($id);
if (!$departement) {
return new JsonResponse(['msg' => 'Department not found'], 404);
}
$res = $departement->getNumero();
$maxLenght = $departement->getCp();
return new JsonResponse(['numero' => $res,'maxLength'=>$maxLenght], 200);
}
}