<?php
namespace App\Controller;
use App\service\servicesGlobale;
use App\Repository\QuestionnaireRepository;
use App\Repository\QuestionsRepository;
use App\Repository\ConfigHeaderRepository;
use App\Repository\QuestionnaireProfileRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Questionnaire;
use App\Entity\Questions;
use App\Entity\QuestionReponse;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Repository\ProfilsRepository;
use App\Entity\ReponseProfil;
use App\Entity\QuestionnaireProfile;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use App\Repository\SystemConfigurationRepository;
class QuestionnairesController extends AbstractController
{
private $etat_cnx ;
public function __construct(EntityManagerInterface $em , servicesGlobale $globalServ , SessionInterface $session )
{
$this->em = $em ;
if(!$globalServ->verifSession()){
$this->etat_cnx = 0 ;
}
else{
$this->etat_cnx = 1 ;
}
$this->session = $session ;
}
function genererCode($length){
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = '';
for($i=0; $i<$length; $i++){
$string .= $chars[rand(0, strlen($chars)-1)];
}
return $string;
}
/**
* @Route("/new_questionnaire", name="new_questionnaire", options = {"expose" = true})
* @Route("/qestionnaire_edit/{id}", name="qestionnaire_edit")
* @Route("/questionnaires", name="questionnaires", methods={"GET","POST"} , options={"expose"=true})
*/
public function index(Request $request , QuestionnaireRepository $QuestionnaireRepository ,
ConfigHeaderRepository $ConfigHeaderRepository , ProfilsRepository $profilesRepository): Response
{
if($this->etat_cnx == 0 ){
return $this->redirectToRoute('login') ;
}
$questionnaires = $QuestionnaireRepository->findBy([], ['created_at' => 'DESC']);
$profiles = $profilesRepository->findAll();
$questionnaire = null ;
if(null !== $request->get('id')){
$questionnaire = $QuestionnaireRepository->find($request->get('id')) ;
}
return $this->render('questionnaires/index.html.twig', [
'questionnaires' => $questionnaires,
'questionnaire' => $questionnaire,
'profiles' => $profiles,
]);
}
/**
* @Route("/delete_questionnaire/{id}", name="delete_questionnaire", options={"expose"=true}, methods={"DELETE"})
*/
public function deleteQuestionnaire(Request $request, Questionnaire $questionnaire): JsonResponse
{
$entityManager = $this->getDoctrine()->getManager();
//dd($questionnaire);
try {
$entityManager->remove($questionnaire);
$entityManager->flush();
// Return a success response
return new JsonResponse(['success' => true]);
} catch (\Exception $e) {
// Handle the exception, e.g., log the error
// Return an error response
return new JsonResponse(['success' => false, 'message' => 'Failed to delete the questionnaire']);
}
}
/**
* @Route("/quiz/{url}", name="quiz", methods={"GET","POST"}, options={"expose"=true})
*/
public function showQuiz(Request $request, QuestionnaireRepository $QuestionnaireRepository, SystemConfigurationRepository $systemConfigurationRepository, ConfigHeaderRepository $ConfigHeaderRepository , $url): Response
{
$systemConfiguration = $systemConfigurationRepository->find(1);
$config_header = $ConfigHeaderRepository->find(2) ;
//dd($config_header);
if ($systemConfiguration && $systemConfiguration->getMaintenance() && $this->etat_cnx == 0) {
return new Response('Dans un état de maintenance, revenez plus tard.', Response::HTTP_FORBIDDEN);
}
//dd($url);
$baseURL = 'https://akoyaconfig.services-unifies.fr/' . $url ;
$questionnaire = $QuestionnaireRepository->findOneBy(['url_questionnaire' => $url]);
if (!$questionnaire) {
throw $this->createNotFoundException('Questionnaire not found');
}
//dd($questionnaire->getQuestions()->toArray());
if ($questionnaire->getEtat() === 'disabled') {
return new Response('Questionnaire is disabled', Response::HTTP_FORBIDDEN);
}
//dd($questionnaire);
return $this->render('questionnaires/frontOffice/quiz.html.twig', [
'questionnaire' => $questionnaire,
'HeaderGeneral' => $config_header->getContenu()
]);
}
/**
* @Route("/findProfile", name="findProfile", methods={"GET","POST"} , options={"expose"=true})
*/
public function findProfile(Request $request, QuestionnaireRepository $QuestionnaireRepository, ProfilsRepository $profilsRepository , SystemConfigurationRepository $systemConfigurationRepository): JsonResponse
{
$requestData = json_decode($request->getContent(), true);
$profilePointsTotal = [];
$systemConfiguration = $systemConfigurationRepository->find(1);
foreach ($requestData as $responseIds) {
foreach ($responseIds as $responseId) {
$response = $this->getDoctrine()->getRepository(QuestionReponse::class)->find($responseId);
if ($response) {
$responseProfilePoints = $response->getProfilePoints();
foreach ($responseProfilePoints as $profilePoint) {
$profileId = $profilePoint['id'];
$profilePoints = intval($profilePoint['points']);
if (!isset($profilePointsTotal[$profileId])) {
$profilePointsTotal[$profileId] = 0;
//dump($profilePointsTotal[$profileId]);
}
$profilePointsTotal[$profileId] += $profilePoints;
}
}
}
}
arsort($profilePointsTotal);
//dd($profilePointsTotal);
$topProfileIds = array_slice(array_keys($profilePointsTotal), 0, 6);
$testModeEnabled = $systemConfiguration ? $systemConfiguration->getModeTest() : false;
$profileDetails = [];
foreach ($topProfileIds as $profileId) {
$profile = $profilsRepository->findBy(['nom_profil' => $profileId]);
if ($profile) {
$profileDetails[] = [
'profile' => $profile[0],
'points' => $profilePointsTotal[$profileId],
'testModeEnabled' => $testModeEnabled,
];
}
}
//dd($profileDetails);
return $this->json($profileDetails);
}
/**
* @Route("/save_questionnaire", name="save_questionnaire", methods={"POST"}, options={"expose"=true})
*/
public function saveQuestionnaire(
Request $request,
QuestionnaireRepository $questionnaireRepository,
EntityManagerInterface $em,
QuestionsRepository $questionRepository,
ProfilsRepository $profilsRepository): JsonResponse
{
//dd($request->request->all());
try {
$nomQuestionnaire = $request->request->get('nom_questionnaire');
$etat = $request->request->get('etat');
$profiles = $request->request->get('profiles');
$urlQuestionnaire = $request->request->get('url_questionnaire');
$meta = $request->request->get('meta');
$presentation = $request->request->get('presentation');
$header = $request->request->get('header');
$questionsData = json_decode($request->request->get('questions'), true);
//dd($request->request->all());
//dd($questionsData);
$codeCouleur = $request->request->get('code_couleur');
$couleurContraste = $request->request->get('couleur_contraste');
if (empty($questionsData['questions'])) {
return new JsonResponse(['error' => 'Vous devez ajouter au moins une question.'], Response::HTTP_BAD_REQUEST);
}
//dd($urlQuestionnaire);
$questionnaire = new Questionnaire();
$questionnaire->setNomQuestionnaire($nomQuestionnaire);
$questionnaire->setEtat($etat);
$questionnaire->setUrlQuestionnaire($urlQuestionnaire);
$questionnaire->setMetaDescription($meta);
$questionnaire->setPresentation($presentation);
$questionnaire->setHeader($header);
$questionnaire->setCodeCouleur($codeCouleur);
$questionnaire->setCouleurContraste($couleurContraste);
$questionnaire->setCreatedAt(new \DateTime());
//dd($urlQuestionnaire);
//$hashedUrl = md5($urlQuestionnaire);
//$questionnaire->sethashedURL($hashedUrl);
foreach ($profiles as $profileId) {
$profile = $profilsRepository->find($profileId);
if ($profile) {
$questionnaireProfile = new QuestionnaireProfile();
$questionnaireProfile->setQuestionnaire($questionnaire);
$questionnaireProfile->setProfil($profile);
$em->persist($questionnaireProfile);
}
}
$em->persist($questionnaire);
//dd($request->request->all());
foreach ($questionsData['questions'] as $questionData) {
$questionsEntity = new Questions();
$questionsEntity->setQuestion($questionData['text']);
$questionsEntity->setNomQuestionnaire($nomQuestionnaire);
$questionsEntity->setQuestionnaire($questionnaire);
$questionsEntity->setNumResponses($questionData['numResponses']);
$em->persist($questionsEntity);
foreach ($questionData['responses'] as $response) {
$responseText = $response['text'];
$questionReponse = new QuestionReponse();
$questionReponse->setQuestion($questionsEntity);
$questionReponse->setContent($responseText);
$profilePoints = [];
foreach ($response['profiles'] as $profile) {
$profileName = $profile['name'];
$profileId = str_replace('input-', '', $profileName);
$points = $profile['value'];
$profilePoints[] = [
'id' => $profileId,
'points' => $points
];
}
$questionReponse->setProfilePoints($profilePoints);
$em->persist($questionReponse);
}
}
$em->flush();
return new JsonResponse(['success' => true, 'questionnaire_id' => $questionnaire->getId()]);
} catch (\Exception $e) {
if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
return new JsonResponse(['error' => 'Cette URL est déjà utilisée. Veuillez en choisir un différent.'], Response::HTTP_CONFLICT);
}
return new JsonResponse(['error' => $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
/**
* @Route("/upload_image", name="upload_image", methods={"POST"})
*/
public function upload_image(
Request $request,
QuestionnaireRepository $questionnaireRepository,
EntityManagerInterface $em,
Filesystem $filesystem
): JsonResponse {
// Load your questionnaire entity here (you need to replace 'Questionnaire' with your actual entity class)
$questionnaireId = $request->request->get('questionnaire_id');
$questionnaire = $questionnaireRepository->find($questionnaireId);
if (!$questionnaire) {
return $this->json(['status' => 'error', 'message' => 'Questionnaire not found']);
}
$uploadDirRoot = $this->getParameter('quiz_image_directory');
if (!$filesystem->exists($uploadDirRoot)) {
$filesystem->mkdir($uploadDirRoot);
}
$imageFile = $request->files->get('img_principale');
if ($imageFile !== null) {
$newFilename = uniqid().'.'.$imageFile->guessExtension();
$imageFile->move($uploadDirRoot, $newFilename);
$questionnaire->setImgPrincipale($newFilename);
$em->persist($questionnaire);
$em->flush();
return $this->json(['status' => 'success', 'message' => 'Image uploaded and questionnaire updated']);
} else {
return $this->json(['status' => 'error', 'message' => 'No image file uploaded']);
}
}
/**
* @Route("/edit_questionnaire/{id}", name="edit_questionnaire", methods={"POST"}, options={"expose"=true})
*/
public function editQuestionnaire(
Request $request,
$id,
EntityManagerInterface $em,
QuestionsRepository $questionRepository,
ProfilsRepository $profilsRepository ,
QuestionnaireRepository $questionnaireRepository,
): JsonResponse {
$requestData = $request->request->all();
$questionsData = json_decode($requestData['questions'], true);
//dd($requestData);
$questionnaire = $em->getRepository(Questionnaire::class)->find($id);
if (!$questionnaire) {
return new JsonResponse(['error' => 'Questionnaire not found.'], 404);
}
//dd($requestData);
// dd($request->files->get('img_principale'));
$uploadDirRoot = $this->getParameter('quiz_image_directory');
$imageFile = $request->files->get('img_principale');
$nomQuestionnaire = $requestData['editQuestionnaireName'];
$etat = $requestData['etat'];
//dd($etat);
$urlQuestionnaire = $requestData['editQuestionnaireURL'];
$metaDescription = $requestData['editQuestionnaireMetaDescription'];
$presentation = $requestData['editQuestionnairePresentation'];
$selectedProfilesJson = $requestData['selectedProfiles'];
$codeCouleur = $requestData['code_couleur'];
$contrastCouleur = $requestData['couleur_contraste'];
$selectedProfiles = json_decode($selectedProfilesJson, true);
/*
$existingQuestionnaire = $questionnaireRepository->findOneBy(['hashedURL' => $urlQuestionnaire]);
if ($existingQuestionnaire) {
$errorMessage = 'Cette URL est déjà utilisée. Veuillez en choisir une autre.';
return new JsonResponse(['error' => $errorMessage], 400);
}
*/
$questionnaire->setNomQuestionnaire($nomQuestionnaire);
$questionnaire->setEtat($etat);
$questionnaire->setUrlQuestionnaire($urlQuestionnaire);
$questionnaire->setMetaDescription($metaDescription);
$questionnaire->setPresentation($presentation);
$questionnaire->setCodeCouleur($codeCouleur);
$questionnaire->setCouleurContraste($contrastCouleur);
//$questionnaire->sethashedURL($urlQuestionnaire);
if ($imageFile) {
$oldImageFilename = $questionnaire->getImgPrincipale();
if ($oldImageFilename && file_exists($uploadDirRoot . $oldImageFilename)) {
unlink($uploadDirRoot . $oldImageFilename);
}
$newFilename = uniqid().'.'.$imageFile->guessExtension();
$imageFile->move($uploadDirRoot, $newFilename);
$questionnaire->setImgPrincipale($newFilename);
$em->persist($questionnaire);
$em->flush();
}
//dd($request->request->all());
foreach ($questionnaire->getQuestionnaireProfiles() as $existingProfile) {
$questionnaire->removeQuestionnaireProfile($existingProfile);
$em->remove($existingProfile);
}
foreach ($selectedProfiles as $profileName) {
$profile = $profilsRepository->findOneBy(['nom_profil' => $profileName]);
if ($profile) {
$questionnaireProfile = new QuestionnaireProfile();
$questionnaireProfile->setQuestionnaire($questionnaire);
$questionnaireProfile->setProfil($profile);
$em->persist($questionnaireProfile);
}
}
if (isset($requestData['newQuestions'])) {
$newQuestionsData = json_decode($requestData['newQuestions'], true);
//dd($newQuestionsData);
foreach ($newQuestionsData as $newQuestionData) {
$newQuestionText = $newQuestionData['question'];
$numResponsesPossible = $newQuestionData['numResponsesPossible'];
//dd($numResponsesPossible);
$newQuestionEntity = new Questions();
$newQuestionEntity->setQuestion($newQuestionText);
$newQuestionEntity->setNomQuestionnaire($nomQuestionnaire);
$newQuestionEntity->setQuestionnaire($questionnaire);
$newQuestionEntity->setNumResponses($numResponsesPossible);
$em->persist($newQuestionEntity);
foreach ($newQuestionData['reponses'] as $newResponse) {
$newResponseText = $newResponse['content'];
$newResponseEntity = new QuestionReponse();
$newResponseEntity->setQuestion($newQuestionEntity);
$newResponseEntity->setContent($newResponseText);
$profilePoints = [];
foreach ($newResponse['profilePoints'] as $profilePoint) {
$profileId = $profilePoint['id'];
$points = $profilePoint['points'];
$selectedProfile = $profilsRepository->findOneBy(['nom_profil' => $profileId]);
if ($selectedProfile) {
$profilePoints[] = [
'id' => $profileId,
'points' => $points
];
}
}
$newResponseEntity->setProfilePoints($profilePoints);
$em->persist($newResponseEntity);
}
}
$em->flush();
}
foreach ($questionsData as $questionData) {
$questionId = $questionData['id'];
$questionText = $questionData['question'];
$deleted = isset($questionData['deleted']) && $questionData['deleted'] === true;
$question = $questionRepository->find($questionId);
$NombreReponse = $questionData['numResponses'];
//dd($NombreReponse);
if ($deleted) {
$question->removeReponse($questionReponse);
$em->remove($question);
}else{
$question->setQuestion($questionText);
$question->setNumResponses($NombreReponse);
foreach ($question->getReponses() as $questionReponse) {
$question->removeReponse($questionReponse);
$em->remove($questionReponse);
}
//$em->flush();
foreach ($questionData['reponses'] as $response) {
$responseText = $response['content'];
$responseEntity = new QuestionReponse();
$responseEntity->setQuestion($question);
$responseEntity->setContent($responseText);
$profilePoints = [];
//dd($response['profilePoints']);
foreach ($response['profilePoints'] as $profilePoint) {
$profileId = $profilePoint['id'];
$points = $profilePoint['points'];
$selectedProfile = $profilsRepository->findOneBy(['nom_profil' => $profileId]);
//dd($points);
//$points = $profile['value'];
//dd($points);
if ($selectedProfile) {
$profilePoints[] = [
'id' => $profileId,
'points' => $points
];
}
}
$responseEntity->setProfilePoints($profilePoints);
$em->persist($responseEntity);
}
}
//$em->flush();
}
$em->persist($questionnaire);
$em->flush();
return new JsonResponse(['success' => true]);
}
/**
* @Route("/module", name="module", options = {"expose" = true})
* @Route("/listeModules", name="listeModules", options = {"expose" = true})
* @Route("/module_edit/{id}", name="module_edit")
*/
/* public function index2(Request $request , ModulesRepository $ModulesRepository , GlobalAdmin $GlobalAdmin , ConfigHeaderRepository $ConfigHeaderRepository ): Response
{
if( ($this->session->get('susrD3p9LjjY86') != 'gA64ya3G5N') && ($request->hasSession()) ){
return $this->redirectToRoute('connexion');
}
$modules = $ModulesRepository->findAll() ;
$module = null ;
$pieces = null;
if(null !== $request->get('id')){
$module = $ModulesRepository->find($request->get('id')) ;
$pieces = $module->getPiecesJointes();
}
$config_header = $ConfigHeaderRepository->findAll()[0];
return $this->render('modules/index.html.twig', [
'modules' => $modules ,
'module' => $module,
'config_header'=>$config_header,
'pieces'=>$pieces
]);
}*/
}