src/Controller/ProfileController.php line 1466

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Certification;
  4. use App\Entity\CompteRecrutement;
  5. use App\Entity\Diplome;
  6. use App\Entity\Enum\EnglishLevel;
  7. use App\Entity\Enum\FrenchRegion;
  8. use App\Entity\Enum\LegalStatus;
  9. use App\Entity\Enum\SkillLevel;
  10. use App\Entity\Experience;
  11. use App\Entity\Profile;
  12. use App\Entity\Skill;
  13. use App\Entity\User;
  14. use App\Form\ProfileFormType;
  15. use App\Form\IntercontratFormType;
  16. use App\Repository\ProfileRepository;
  17. use App\Repository\UserRepository;
  18. use App\Service\Upload\AvatarUploader;
  19. use App\Service\Upload\PDFUploader;
  20. use Doctrine\Common\Collections\ArrayCollection;
  21. use Doctrine\ORM\EntityManagerInterface;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  23. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  24. use Symfony\Component\HttpFoundation\JsonResponse;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\HttpFoundation\Response;
  27. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  28. use Symfony\Component\Routing\Annotation\Route;
  29. /**
  30.  * @Route("/tableau-de-bord/profile")
  31.  */
  32. class ProfileController extends AbstractController
  33. {
  34.     /**
  35.      * @Route("/", name="profile_list", methods={"GET"})
  36.      * @IsGranted("ROLE_SOCIETY")
  37.      * @param ProfileRepository $profileRepository
  38.      * @return Response
  39.      */
  40.     public function index(
  41.         ProfileRepository $profileRepository,
  42.         Request           $request,
  43.         UserRepository    $userRepository
  44.     ): Response {
  45.         $idCompte $request->query->get("compte");
  46.         /* @var User $user */
  47.         $user $this->getUser();
  48.         $society $user->getSociety();
  49.         $package $society->getPackage();
  50.         // if (!$society->canViewProfile() || $society->getPackageExpireAt() < new \DateTime()) {
  51.         //     $this->addFlash('package_error', "Acheter un package supérieur pour voir les intercontrats");
  52.         //
  53.         //     return $this->redirectToRoute('dashboard');
  54.         // }
  55.         $profils $profileRepository->findBy(['user' => $user]);
  56.         // COMPTE RECRUTEUR
  57.         if ($user->getCompteSociety()) {
  58.             $profils $profileRepository->findBy([
  59.                 'userRecruteur' => $user
  60.             ]);
  61.         } else {
  62.             if (!$idCompte) {
  63.                 $idCompte "main";
  64.             }
  65.             //  AFFICHER DEPUIS ID RECRUTEUR
  66.             if (isset($idCompte) && $idCompte != "all") {
  67.                 $selectedCompte $userRepository->findOneBy([
  68.                     "id" => $idCompte
  69.                 ]);
  70.                 $profils $profileRepository->findBy([
  71.                     'userRecruteur' => $selectedCompte,
  72.                     'user' => $society->getUser()
  73.                 ]);
  74.             }
  75.             // AFFICHER SES PRPOPRES OFFRES
  76.             if ($idCompte == "main") {
  77.                 $allProfils $profileRepository->findBy(['user' => $user]);
  78.                 $profils = [];
  79.                 foreach ($allProfils as $profile) {
  80.                     if (!$profile->getUserRecruteur()) {
  81.                         $profils[] = $profile;
  82.                     }
  83.                 };
  84.             }
  85.         }
  86.         /** @var CompteRecrutement[] $compteRecrutActif */
  87.         $compteRecrutActif = [];
  88.         if (!empty($society->getCompteRecrutements())) {
  89.             foreach ($society->getCompteRecrutements() as $compteRecrutement) {
  90.                 if ($compteRecrutement->getUserRecruiteur()) {
  91.                     $compteRecrutActif[] = $compteRecrutement;
  92.                 }
  93.             }
  94.         }
  95.         return $this->render('profile/index.html.twig', [
  96.             'profiles' => $profils,
  97.             'package' => $package,
  98.             'compteRecrutActif' => $compteRecrutActif,
  99.             "selectedCompte" => $idCompte
  100.         ]);
  101.     }
  102.     /**
  103.      * @Route("/new_before", name="profile_new_before", methods={"GET", "POST"})
  104.      */
  105.     function new_before(Request $requestSessionInterface $sessionEntityManagerInterface $entityManagerPDFUploader $pdfUploaderAvatarUploader $avatarUploaderProfileRepository $profileRepository): Response
  106.     {
  107.         /* @var User $user */
  108.         $user $this->getUser();
  109.         $society $user->getSociety();
  110.         $package $society->getPackage();
  111.         // Guard: require an active 'month' or 'year' package to create intercontrats
  112.         $allowedPackages = ['month''year'];
  113.         if (!in_array($package$allowedPackagestrue) || !$society->hasActivePackage()) {
  114.             $this->addFlash('package_error'"Il faut avoir un package actif pour pouvoir créer des intercontrats.");
  115.             return $this->redirectToRoute('active_package');
  116.         }
  117.         // if (!$society->canViewProfile() || $society->getPackageExpireAt() < new \DateTime()) {
  118.         //     $this->addFlash('package_error', "Souscrivez à un package supérieur pour déposer des annonces entre entreprises. ");
  119.         //
  120.         //     return $this->redirectToRoute('dashboard');
  121.         // }
  122.         if ($user->isCompteTestIsNotActive()) {
  123.             $this->addFlash('package_error'"Vous ne pouvez pas créer d'Intercontrat. Votre compte a été désactivé par l'administrateur de la société.");
  124.             return $this->redirectToRoute('dashboard');
  125.         }
  126.         $intercontratUne abs((int)$user->getSociety()->getIntercontratUne() - (int)$profileRepository->countIntercontratUne($user));
  127.         $profile = new Profile();
  128.         $profile->setIsIntercontrat(true);
  129.         $profile->setUser($user);
  130.         $profile->setUrl('');
  131.         // COMPTE RECRUTEUR
  132.         if ($user->getCompteSociety()) {
  133.             $profile->setUserRecruteur($user);
  134.             $profile->setUser($user->getSociety()->getUser());
  135.         }
  136.         if ($request->getMethod() == 'POST') {
  137.             // $cvFile = $request->files->get('cv_file');
  138.             // if ($cvFile) {
  139.             //     $uploadDir = $this->getParameter('pdf_directory');
  140.             //     $newFilename = 'cv-' . uniqid() . '.' . $cvFile->guessExtension();
  141.             //     $cvFile->move($uploadDir, $newFilename);
  142.             //     $session->remove('cv_file');
  143.             //     $session->set('cv_file', $newFilename);
  144.             // }
  145.             $cvFile $request->files->get('cv_file');
  146.             if ($cvFile) {
  147.                 $uploadDir $this->getParameter('pdf_directory');
  148.                 // Récupérer le nom d'origine du fichier
  149.                 $originalFilename pathinfo($cvFile->getClientOriginalName(), PATHINFO_FILENAME);
  150.                 $extension $cvFile->guessExtension();
  151.                 // Créez le nouveau nom de fichier en combinant le nom d'origine avec l'extension
  152.                 $newFilename $originalFilename '.' $extension;
  153.                 // Déplacer le fichier téléchargé vers le répertoire de destination
  154.                 $cvFile->move($uploadDir$newFilename);
  155.                 // Gérer la session
  156.                 $session->remove('cv_file');
  157.                 $session->set('cv_file'$newFilename);
  158.             }
  159.             return $this->redirectToRoute('profile_new');
  160.         }
  161.         return $this->renderForm('profile/new_before.html.twig', [
  162.             'profile' => $profile,
  163.             'isIntercontrat' => true,
  164.             'intercontratUne' => $intercontratUne,
  165.             'regionjson' => json_encode(FrenchRegion::REGION_DEPARTEMENTJSON_UNESCAPED_UNICODE),
  166.             'package' => $package
  167.         ]);
  168.     }
  169.     /**
  170.      * @Route("/new", name="profile_new", methods={"GET", "POST"})
  171.      * @param Request $request
  172.      * @param EntityManagerInterface $entityManager
  173.      * @param PDFUploader $pdfUploader
  174.      * @param AvatarUploader $avatarUploader
  175.      * @param ProfileRepository $profileRepository
  176.      * @return Response
  177.      */
  178.     function new(Request $requestSessionInterface $sessionEntityManagerInterface $entityManagerPDFUploader $pdfUploaderAvatarUploader $avatarUploaderProfileRepository $profileRepository): Response
  179.     {
  180.         $jsonData $session->get('generated_content');
  181.         $cv_path $session->get('cv_file');
  182.         /* @var User $user */
  183.         $user $this->getUser();
  184.         $society $user->getSociety();
  185.         $package $society->getPackage();
  186.         if (!$society->canViewProfile() || $society->getPackageExpireAt() < new \DateTime()) {
  187.             $this->addFlash('package_error'"Souscrivez à un package supérieur pour déposer des annonces entre entreprises. ");
  188.             return $this->redirectToRoute('dashboard');
  189.         }
  190.         if ($user->isCompteTestIsNotActive()) {
  191.             $this->addFlash('package_error'"Vous ne pouvez pas créer d'Intercontrat. Votre compte a été désactivé par l'administrateur de la société.");
  192.             return $this->redirectToRoute('dashboard');
  193.         }
  194.         $intercontratUne abs((int)$user->getSociety()->getIntercontratUne() - (int)$profileRepository->countIntercontratUne($user));
  195.         $profile = new Profile();
  196.         $profile->setIsIntercontrat(true);
  197.         $profile->setUser($user);
  198.         $profile->setUrl('');
  199.         $profile->setCdi(false);
  200.         // COMPTE RECRUTEUR
  201.         if ($user->getCompteSociety()) {
  202.             $profile->setUserRecruteur($user);
  203.             $profile->setUser($user->getSociety()->getUser());
  204.         }
  205.         $existing_file false;
  206.         $modalEnreg false;
  207.         if ($jsonData !== null) {
  208.             $modalEnreg true;
  209.             // dd($jsonData);
  210.             $data json_decode($jsonDatatrue);
  211.             $existing_file true;
  212.             if (isset($data['Poste'])) $profile->setTitle($data['Poste']);
  213.             if (isset($data['nom'])) $profile->setName($data['nom']);
  214.             if (isset($data['prenom'])) $profile->setFirstname($data['prenom']);
  215.             if (isset($data['tjm']) && $data['tjm'] !== "" && (int)$data['tjm'] !== 0) {
  216.                 $profile->setCost((int)$data['tjm']);
  217.             }
  218.             if (isset($data['anglais'])) $profile->setEnglishLevel($data['anglais']);
  219.             if (isset($cv_path)) $profile->setCvFile($cv_path);
  220.             if (isset($cv_path)) $profile->setCvname($cv_path);
  221.             if (isset($data['cp_ville'])) $profile->setLocation($data['cp_ville']);
  222.             $skills = [];
  223.             if (isset($data['Compétences'])) {
  224.                 foreach ($data['Compétences'] as $skill => $level) {
  225.                     // Vérifie que le nom ne contient pas uniquement des chiffres
  226.                     if (!preg_match('/^\d+$/'$skill)) {
  227.                         // Convertir le niveau de texte en valeur numérique, ou utiliser 'Débutant' par défaut
  228.                         $numericLevel SkillLevel::LIST[$level] ?? SkillLevel::BEGINNER;
  229.                         $skills[] = [
  230.                             'name' => $skill,
  231.                             'level' => $numericLevel
  232.                         ];
  233.                     }
  234.                 }
  235.                 foreach ($skills as $skillData) {
  236.                     $skill = new Skill();
  237.                     $skill->setName($skillData['name']);
  238.                     $skill->setLevel($skillData['level']);
  239.                     $profile->addSkill($skill);
  240.                 }
  241.             }
  242.             if (isset($data['region'])) {
  243.                 $mobility $data['region'];
  244.                 if (is_string($mobility)) {
  245.                     // Convert string to an array, assuming a comma-separated list
  246.                     $mobility explode(','$mobility);
  247.                 }
  248.                 // Set mobility only if it's an array
  249.                 if (is_array($mobility)) {
  250.                     $profile->setMobility($mobility);
  251.                 } else {
  252.                     $profile->setMobility(null); // Or handle the error appropriately
  253.                 }
  254.             } else {
  255.                 $profile->setMobility(null);
  256.             }
  257.             if (isset($data['année_experience'])) $profile->setExperienceNumber($data['année_experience']);
  258.             if (isset($data['diplômes'])) {
  259.                 $diplomeData $data['diplômes'];
  260.             } else {
  261.                 $diplomeData null// Ou définir une valeur par défaut appropriée
  262.             }
  263.             // dd($diplomeData);
  264.             if (!empty($diplomeData)) {
  265.                 $newDiplome = new Diplome();
  266.                 if (array_values($diplomeData) !== $diplomeData) {
  267.                     $newDiplome->setTitle($diplomeData['title'])
  268.                         ->setUniversity($diplomeData['university'] ?? '')
  269.                         ->setLevel($diplomeData['level'] ?? '');
  270.                     if (isset($diplomeData['obtentionYear']) && is_numeric($diplomeData['obtentionYear'])) {
  271.                         $obtentionYear = (int)$diplomeData['obtentionYear'];
  272.                         error_log('Obtention Year: ' $obtentionYear);
  273.                         $newDiplome->setObtentionYear($obtentionYear);
  274.                     }
  275.                     $profile->addDiplome($newDiplome);
  276.                 } else {
  277.                     foreach ($diplomeData as $diplome) {
  278.                         $newDiplome = new Diplome();
  279.                         $newDiplome->setTitle($diplome['title'])
  280.                             ->setUniversity($diplome['university'] ?? '')
  281.                             ->setLevel($diplome['level'] ?? '');
  282.                         if (isset($diplome['obtentionYear']) && is_numeric($diplome['obtentionYear'])) {
  283.                             $obtentionYear = (int)$diplome['obtentionYear'];
  284.                             error_log('Obtention Year: ' $obtentionYear);
  285.                             $newDiplome->setObtentionYear($obtentionYear);
  286.                         }
  287.                         $profile->addDiplome($newDiplome);
  288.                     }
  289.                 }
  290.             }
  291.             // $profile->setPhone(json_decode($jsonData, true)['telephone']);
  292.             if (isset($data['experience'])) {
  293.                 $experienceData $data['experience'];
  294.             } else {
  295.                 $experienceData null// Ou définir une valeur par défaut appropriée
  296.             }
  297.             if (!empty($experienceData)) {
  298.                 // Check if it's a single experience or an array of experiences
  299.                 if (isset($experienceData['title'])) {
  300.                     // Single experience object, handle it directly
  301.                     $experienceData = [$experienceData];
  302.                 }
  303.                 // Process the JSON data and add experiences to the profile
  304.                 foreach ($experienceData as $experience) {
  305.                     $newExperience = new Experience();
  306.                     $newExperience->setEmployer($experience['employer'] ?? '');
  307.                     // Set end_at to the last day of the current year if empty
  308.                     if (empty($experience['end_at'])) {
  309.                         $currentYear date('Y');
  310.                         $endAt = new \DateTime("$currentYear-12-31");
  311.                     } else {
  312.                         $endAt = new \DateTime($experience['end_at']);
  313.                     }
  314.                     $newExperience->setEndAt($endAt);
  315.                     if (isset($experience['environment_tech'])) {
  316.                         if (is_array($experience['environment_tech'])) {
  317.                             $environmentTech implode(', '$experience['environment_tech']);
  318.                         } else {
  319.                             $environmentTech $experience['environment_tech'];
  320.                         }
  321.                     } else {
  322.                         $environmentTech ''// Valeur par défaut si 'environment_tech' n'existe pas
  323.                     }
  324.                     if (isset($experience['missions'])) {
  325.                         if (is_array($experience['missions'])) {
  326.                             // Convertir le tableau en chaîne de caractères avec des sauts de ligne
  327.                             $missions array_map(function ($mission) {
  328.                                 if (is_array($mission)) {
  329.                                     // Gérer les tableaux multidimensionnels en les convertissant en une chaîne
  330.                                     return implode(", "$mission);
  331.                                 } else {
  332.                                     return $mission;
  333.                                 }
  334.                             }, $experience['missions']);
  335.                             // Convertir le tableau de missions en une chaîne de caractères
  336.                             $missions implode("\n"$missions);
  337.                         } else {
  338.                             // Vérifier si 'missions' est déjà une chaîne de caractères
  339.                             $missions $experience['missions'];
  340.                         }
  341.                     } else {
  342.                         // Définir une valeur par défaut si 'missions' n'existe pas
  343.                         $missions '';
  344.                     }
  345.                     $newExperience->setEnvironment($environmentTech)
  346.                         ->setMissions($missions)
  347.                         ->setStartAt(new \DateTime($experience['start_at'] ?? null));
  348.                     // Assurez-vous que 'title' est toujours une chaîne de caractères
  349.                     $title $experience['title'] ?? '';
  350.                     if (!is_string($title)) {
  351.                         $title '';
  352.                     }
  353.                     $newExperience->setTitle($title);
  354.                     $profile->addExperience($newExperience);
  355.                 }
  356.             }
  357.             // Vérifier si la clé 'certifications' existe
  358.             if (isset($data['certifications'])) {
  359.                 $certificationData $data['certifications'];
  360.             } else {
  361.                 $certificationData null// Ou définir une valeur par défaut appropriée
  362.             }
  363.             if (isset($data['anglais'])) {
  364.                 $anglais $data['anglais'];
  365.                 // Mapper des valeurs possibles aux niveaux de la classe
  366.                 $levelMapping = [
  367.                     'notions' => EnglishLevel::NOTION,
  368.                     'technique' => EnglishLevel::TECHNIQUE,
  369.                     'courant' => EnglishLevel::COURANT,
  370.                 ];
  371.                 $englishLevel $levelMapping[strtolower($anglais)] ?? EnglishLevel::NOTION;  // Niveau par défaut
  372.                 // dd($englishLevel);
  373.                 $profile->setEnglishLevel($englishLevel);
  374.             }
  375.             if (!empty($certificationData)) {
  376.                 // Check if it's a single $certificationDat or an array of certificationData
  377.                 if (isset($certificationData['title'])) {
  378.                     // Single experience object, handle it directly
  379.                     $certificationData = [$certificationData];
  380.                 }
  381.                 foreach ($certificationData as $certification) {
  382.                     $newCertification = new Certification();
  383.                     $newCertification->setTitle($certification['title'] ?? '')
  384.                         ->setEtablissement($certification['etablissement'] ?? '');
  385.                     // Vérification et conversion de l'année d'obtention
  386.                     if (isset($certification['obtention_year']) && is_numeric($certification['obtention_year'])) {
  387.                         $obtentionYear = (int)$certification['obtention_year'];
  388.                         error_log('Obtention Year: ' $obtentionYear);
  389.                         $newCertification->setObtentionYear($obtentionYear);
  390.                     } else {
  391.                         // Définir une valeur par défaut appropriée ou gérer l'erreur
  392.                         error_log('Invalid Obtention Year: ' . (isset($certification['obtention_year']) ? $certification['obtention_year'] : 'not set'));
  393.                         $newCertification->setObtentionYear(0);
  394.                     }
  395.                     $profile->addCertification($newCertification);
  396.                 }
  397.             }
  398.             // Vérifier si la clé 'certifications' existe
  399.             if (isset($data['présentation'])) {
  400.                 $presentationData $data['présentation'];
  401.             } else {
  402.                 $presentationData null// Ou définir une valeur par défaut appropriée
  403.             }
  404.             if (!empty($presentationData)) {
  405.                 $profile->setAbout($presentationData);
  406.             }
  407.             if (isset($data['url_Linkedin'])) {
  408.                 $linkedInData $data['url_Linkedin'];
  409.             } else {
  410.                 $linkedInData null// Ou définir une valeur par défaut appropriée
  411.             }
  412.             if (!empty($linkedInData)) {
  413.                 $profile->setLinkedin($linkedInData);
  414.             }
  415.             // dd($profile);
  416.         }
  417.         $form $this->createForm(ProfileFormType::class, $profile, [
  418.             'isNew' => true,
  419.             'existingFile' => $existing_file
  420.         ]);
  421.         $form->handleRequest($request);
  422.         if ($form->isSubmitted()) $modalEnreg false;
  423.         if ($form->isSubmitted() && $form->isValid()) {
  424.             $experiences $profile->getExperiences();
  425.             $diplomes $profile->getDiplomes();
  426.             $certifications $profile->getCertifications();
  427.             $skills $profile->getSkills();
  428.             if (!empty($user->getPhoto())) {
  429.                 $profile->setPhoto($user->getPhoto());
  430.                 $pdfFile $form->get('cv_file')->getData();
  431.                 if (isset($pdfFile) && is_object($pdfFile)) {
  432.                     $pdfSavedFile $pdfUploader->upload($pdfFile);
  433.                     if ($pdfSavedFile) {
  434.                         $profile->setCvname($pdfSavedFile['name']);
  435.                         $profile->setCvFile($pdfSavedFile['path']);
  436.                     }
  437.                 }
  438.             } else {
  439.                 $this->handleUpload($profile$form$pdfUploader$avatarUploader);
  440.             }
  441.             $profile->resetContent();
  442.             $entityManager->persist($profile);
  443.             foreach ($skills as $skill) {
  444.                 $skill->setProfile($profile);
  445.                 $entityManager->persist($skill);
  446.             }
  447.             foreach ($experiences as $experience) {
  448.                 $experience->setProfile($profile);
  449.                 $entityManager->persist($experience);
  450.             }
  451.             foreach ($diplomes as $diplome) {
  452.                 $diplome->setProfile($profile);
  453.                 $entityManager->persist($diplome);
  454.             }
  455.             foreach ($certifications as $certification) {
  456.                 $certification->setProfile($profile);
  457.                 $entityManager->persist($certification);
  458.             }
  459.             $entityManager->flush();
  460.             $profile->updateSlug();
  461.             $entityManager->persist($profile);
  462.             $entityManager->flush();
  463.             $session->remove('generated_content');
  464.             $session->remove('cv_file');
  465.             return $this->redirectToRoute('profile_list', [], Response::HTTP_SEE_OTHER);
  466.         }
  467.         return $this->renderForm('profile/new.html.twig', [
  468.             'profile' => $profile,
  469.             'modalEnreg' => $modalEnreg,
  470.             'form' => $form,
  471.             'isIntercontrat' => true,
  472.             'intercontratUne' => $intercontratUne,
  473.             'regionjson' => json_encode(FrenchRegion::REGION_DEPARTEMENTJSON_UNESCAPED_UNICODE),
  474.             'package' => $package
  475.         ]);
  476.     }
  477.     private function handleUpload(Profile $profile$form$pdfUploader$avatarUploader)
  478.     {
  479.         $pdfFile $form->get('cv_file')->getData();
  480.         if (isset($pdfFile) && is_object($pdfFile)) {
  481.             $pdfSavedFile $pdfUploader->upload($pdfFile);
  482.             if ($pdfSavedFile) {
  483.                 $profile->setCvname($pdfSavedFile['name']);
  484.                 $profile->setCvFile($pdfSavedFile['path']);
  485.             }
  486.         }
  487.         $avatarFile $form->get('photo')->getData();
  488.         if (isset($avatarFile)) {
  489.             $avatarSavedFile $avatarUploader->upload($avatarFile);
  490.             if ($avatarSavedFile) {
  491.                 $profile->setPhoto($avatarSavedFile);
  492.             }
  493.         }
  494.     }
  495.     /**
  496.      * @Route("/cv", name="edit_talent_profile", methods={"GET", "POST"})
  497.      */
  498.     public function editTalent(
  499.         Request                $request,
  500.         EntityManagerInterface $entityManager,
  501.         PDFUploader            $pdfUploader,
  502.         AvatarUploader         $avatarUploader
  503.     ): Response {
  504.         /* @var User $user */
  505.         $user $this->getUser();
  506.         $profile $user->getUniqueProfile();
  507.         $profile->setIsVisible(true);
  508.         $cvInitialFileName $profile->getCvFile();
  509.         $isNew false;
  510.         $isCdi false;
  511.         if (!$profile->getId()) {
  512.             $isNew true;
  513.             $profile->setUrl($profile->getName());
  514.         }
  515.         if ($profile->getCdi() === 'Oui') {
  516.             $isCdi true;
  517.         }
  518.         $profileForm $request->get('profile_form');
  519.         $originalSkills = new ArrayCollection();
  520.         $originalExperiences = new ArrayCollection();
  521.         $originalDiplomes = new ArrayCollection();
  522.         $originalCertifications = new ArrayCollection();
  523.         foreach ($profile->getSkills() as $skill) {
  524.             $originalSkills->add($skill);
  525.         }
  526.         foreach ($profile->getExperiences() as $experience) {
  527.             $originalExperiences->add($experience);
  528.         }
  529.         foreach ($profile->getDiplomes() as $diplome) {
  530.             $originalDiplomes->add($diplome);
  531.         }
  532.         foreach ($profile->getCertifications() as $certification) {
  533.             $originalCertifications->add($certification);
  534.         }
  535.         $form $this->createForm(ProfileFormType::class, $profile, ['isNew' => $isNew'isCdi' => $isCdi]);
  536.         $form->handleRequest($request);
  537.         $cvFileNameValueRequest $profile->getCvFile();
  538.         if ($cvFileNameValueRequest == "" || $cvFileNameValueRequest == null) {
  539.             $profile->setCvFile($cvInitialFileName);
  540.         }
  541.         if ($form->isSubmitted() && $form->isValid()) {
  542.             if (!$profile->getId()) {
  543.                 $entityManager->persist($profile);
  544.             }
  545.             foreach ($originalSkills as $skill) {
  546.                 if (false === $profile->getSkills()->contains($skill)) {
  547.                     $entityManager->remove($skill);
  548.                 }
  549.             }
  550.             foreach ($originalExperiences as $experience) {
  551.                 if (false === $profile->getExperiences()->contains($experience)) {
  552.                     $entityManager->remove($experience);
  553.                 }
  554.             }
  555.             foreach ($originalDiplomes as $diplome) {
  556.                 if (false === $profile->getDiplomes()->contains($diplome)) {
  557.                     $entityManager->remove($diplome);
  558.                 }
  559.             }
  560.             foreach ($originalCertifications as $certification) {
  561.                 if (false === $profile->getCertifications()->contains($certification)) {
  562.                     $entityManager->remove($certification);
  563.                 }
  564.             }
  565.             foreach ($profile->getSkills() as $skill) {
  566.                 $skill->setProfile($profile);
  567.                 $entityManager->persist($skill);
  568.             }
  569.             foreach ($profile->getExperiences() as $experience) {
  570.                 $experience->setProfile($profile);
  571.                 $entityManager->persist($experience);
  572.             }
  573.             foreach ($profile->getDiplomes() as $diplome) {
  574.                 $diplome->setProfile($profile);
  575.                 $entityManager->persist($diplome);
  576.             }
  577.             foreach ($profile->getCertifications() as $certification) {
  578.                 $certification->setProfile($profile);
  579.                 $entityManager->persist($certification);
  580.             }
  581.             $this->handleUpload($profile$form$pdfUploader$avatarUploader);
  582.             if ($user->isFreelance()) {
  583.                 $user->setPhoto($profile->getPhoto());
  584.             }
  585.             if (!empty($profileForm['name'])) {
  586.                 $user->setLastname($profileForm['name']);
  587.             }
  588.             if (!empty($profileForm['firstname'])) {
  589.                 $user->setFirstname($profileForm['firstname']);
  590.             }
  591.             $entityManager->flush();
  592.             $this->addFlash('success''Profil mis à jour');
  593.             return $this->redirectToRoute('edit_talent_profile', [], Response::HTTP_SEE_OTHER);
  594.         }
  595.         if ($form->isSubmitted() && !$form->isValid()) {
  596.             $this->addFlash('error''Un ou plusieurs champs sont incorrect.');
  597.         }
  598.         return $this->render('profile/edit.html.twig', [
  599.             'modalEnreg' => false,
  600.             'profile' => $profile,
  601.             'form' => $form->createView(),
  602.             'isIntercontrat' => false,
  603.             'regionjson' => json_encode(FrenchRegion::REGION_DEPARTEMENTJSON_UNESCAPED_UNICODE),
  604.         ]);
  605.     }
  606.     /**
  607.      * @Route("/complete_before/{id_user}/{id_data}/{cv_file}/{isIntercontrat}", name="complete_resume_profile_before", methods={"GET", "POST"}, defaults={"id_user"=null,"id_data"=null,"cv_file"=null,"isIntercontrat"=0})
  608.      */
  609.     public function completeResumeBefore(
  610.         ?int $id_user,  // L'argument id_user est maintenant facultatif
  611.         ?string $id_data,  // L'argument id_data est maintenant facultatif
  612.         ?string $cv_file,  // L'argument cv_file est maintenant facultatif
  613.         ?int $isIntercontrat,  // L'argument isIntercontrat est maintenant facultatif
  614.         Request $request,
  615.         EntityManagerInterface $entityManager,
  616.         PDFUploader $pdfUploader,
  617.         AvatarUploader $avatarUploader,
  618.         SessionInterface $session
  619.     ): Response {
  620.         // Si un id_user est fourni, on cherche l'utilisateur correspondant
  621.         if ($isIntercontrat === 0) {
  622.             if ($id_user !== null) {
  623.                 $user $entityManager->getRepository(User::class)->find($id_user);
  624.                 if ($id_data !== null) {
  625.                     // récuperer dans $this->getParameter('cv_status_directory') . '/' . $uniqueId . '.json' sur la clé content , donc ['content'];
  626.                     $data file_get_contents($this->getParameter('cv_status_directory') . '/' $id_data '.json');
  627.                     $dataArray json_decode($datatrue);
  628.                     $data $dataArray['content'] ?? null// Utiliser une valeur par défaut si 'content' n'existe pas
  629.                     $data json_decode($datatrue);
  630.                     $cvFile $cv_file;
  631.                 }
  632.                 if (!$user) {
  633.                     // Si l'utilisateur n'est pas trouvé, vous pouvez retourner une erreur ou rediriger
  634.                     throw $this->createNotFoundException('Utilisateur non trouvé');
  635.                 }
  636.             } else {
  637.                 /* @var User $user */
  638.                 $user $this->getUser();
  639.                 $jsonData $session->get('generated_content'null);
  640.                 $data json_decode($jsonDatatrue);
  641.                 $cvFile $session->get('cv_file');
  642.             }
  643.             $profile $user->getUniqueProfile();
  644.         } else {
  645.             $user $entityManager->getRepository(User::class)->find($id_user);
  646.             // Si isIntercontrat est 1, on crée un nouveau profil
  647.             $profile = new Profile();
  648.             $profile->setIsIntercontrat(true);
  649.             $profile->setUser($user);
  650.             $profile->setUrl('');
  651.             $profile->setCdi(false);
  652.             $cvFile $cv_file;
  653.             $data file_get_contents($this->getParameter('cv_status_directory') . '/' $id_data '.json');
  654.             $dataArray json_decode($datatrue);
  655.             $data $dataArray['content'] ?? null// Utiliser une valeur par défaut si 'content' n'existe pas
  656.             $data json_decode($datatrue);
  657.         }
  658.         // REDIRECT IF COMPLETE
  659.         if ($profile->getTitle() && $isIntercontrat === 0) {
  660.             return $this->redirectToRoute("complete_first_edit");
  661.         }
  662.         $profile->setContrats(null);
  663.         $profile->setIsVisible(true);
  664.         $isNew false;
  665.         if (!$profile->getId() && $isIntercontrat === 0) {
  666.             $isNew true;
  667.             $profile->setUrl($profile->getName());
  668.         }
  669.         $profile->setCvname($cvFile);
  670.         $profile->setCvFile($cvFile);
  671.         $profile->setCdi('Non');
  672.         $profile->setDisponibility('Immédiate');
  673.         // dd($data['Compétences']);
  674.         if (!empty($data['Compétences'])) {
  675.             foreach ($data['Compétences'] as $competence => $levelName) {
  676.                 $newCompetence = new Skill();
  677.                 $newCompetence->setName($competence);
  678.                 // Utilisation de SkillLevel::LIST pour convertir le nom du niveau en entier
  679.                 $level is_string($levelName) && isset(SkillLevel::LIST[$levelName])
  680.                     ? SkillLevel::LIST[$levelName]
  681.                     : SkillLevel::BEGINNER;
  682.                 // Par défaut 'Débutant' si le niveau n'est pas trouvé
  683.                 $newCompetence->setLevel($level);
  684.                 $profile->addSkill($newCompetence);
  685.             }
  686.         }
  687.         (!empty($data['tjm']) && $data['tjm'] != '') ? $profile->setCost((int)$data['tjm']) : $profile->setCost(0);
  688.         (!empty($data['region']) && $data['region'] != '' && $data['region'] != 'Pas en France' && !empty($data['cp_ville'])) ? $profile->setMobility([$data['region']]) : $profile->setMobility(["Toute la France"]);
  689.         (!empty($data['anglais'])) ? $profile->setEnglishLevel($data['anglais']) : $profile->setEnglishLevel(EnglishLevel::NOTION);
  690.         // !empty($data['legalStatus']) ? $profile->setLegalStatus($data['legalStatus']) : $profile->setLegalStatus(LegalStatus::RELFEXION);
  691.         !empty($data['legalStatus']) && $data['legalStatus'] !== "En réflexion" $profile->setLegalStatus($data['legalStatus']) : $profile->setLegalStatus('');
  692.         (!empty($data['année_experience'])) ? $profile->setExperienceNumber($data['année_experience']) : $profile->setExperienceNumber('N/A');
  693.         (!empty($data['cp_ville'])) ? $profile->setLocation($data['cp_ville']) : $profile->setLocation('N/A');
  694.         (!empty($data['Poste'])) ? $profile->setTitle($data['Poste']) : $profile->setTitle('N/A');
  695.         (!empty($data['nom'])) ? $profile->setName($data['nom']) : $profile->setName('Anonyme');
  696.         (!empty($data['prenom'])) ? $profile->setFirstname($data['prenom']) : $profile->setFirstname('Anonyme');
  697.         if (isset($data['diplômes'])) {
  698.             $diplomeData $data['diplômes'];
  699.         } else {
  700.             $diplomeData null// Ou définir une valeur par défaut appropriée
  701.         }
  702.         // dd($diplomeData);
  703.         if (!empty($diplomeData)) {
  704.             $newDiplome = new Diplome();
  705.             if (array_values($diplomeData) !== $diplomeData) {
  706.                 $newDiplome->setTitle($diplomeData['title'])
  707.                     ->setUniversity($diplomeData['university'] ?? '')
  708.                     ->setLevel($diplomeData['level'] ?? '');
  709.                 if (isset($diplomeData['obtentionYear']) && is_numeric($diplomeData['obtentionYear'])) {
  710.                     $obtentionYear = (int)$diplomeData['obtentionYear'];
  711.                     error_log('Obtention Year: ' $obtentionYear);
  712.                     $newDiplome->setObtentionYear($obtentionYear);
  713.                 }
  714.                 $profile->addDiplome($newDiplome);
  715.             } else {
  716.                 foreach ($diplomeData as $diplome) {
  717.                     $newDiplome->setTitle($diplome['title'])
  718.                         ->setUniversity($diplome['university'] ?? '')
  719.                         ->setLevel($diplome['level'] ?? '');
  720.                     if (isset($diplome['obtentionYear']) && is_numeric($diplome['obtentionYear'])) {
  721.                         $obtentionYear = (int)$diplome['obtentionYear'];
  722.                         error_log('Obtention Year: ' $obtentionYear);
  723.                         $newDiplome->setObtentionYear($obtentionYear);
  724.                     }
  725.                     $profile->addDiplome($newDiplome);
  726.                 }
  727.             }
  728.         }
  729.         $profile->setPhone(empty($data['telephone'] ?? 'N/A') ?? $profile->setPhone('Non spécifié'));
  730.         if (isset($data['experience'])) {
  731.             $experienceData $data['experience'];
  732.         } else {
  733.             $experienceData null// Ou définir une valeur par défaut appropriée
  734.         }
  735.         if (!empty($experienceData)) {
  736.             if (isset($experienceData['title'])) {
  737.                 // Single $experienceDataapeta object, handle it directly
  738.                 $experienceData = [$experienceData];
  739.             }
  740.             // Process the JSON data and add experiences to the profile
  741.             foreach ($experienceData as $experience) {
  742.                 $newExperience = new Experience();
  743.                 $newExperience->setEmployer($experience['employer'] ?? '');
  744.                 if (!empty($experience['poste_actuel']) && strtolower($experience['poste_actuel'] == "oui")) {
  745.                     $newExperience->setActualyHere(true);
  746.                 }
  747.                 // Set end_at to the last day of the current year if empty
  748.                 if (empty($experience['end_at']) || (!empty($experience['poste_actuel']) && strtolower($experience['poste_actuel'] == "oui"))) {
  749.                     $currentYear date('Y');
  750.                     // $endAt = new \DateTime("$currentYear-12-31");
  751.                     $endAt null;
  752.                 } else {
  753.                     try {
  754.                         $endAt = new \DateTime($experience['end_at']);
  755.                     } catch (\Exception $e) {
  756.                         // Handle invalid date format by setting a default date
  757.                         // $endAt = new \DateTime("$currentYear-12-31");
  758.                         $endAt null;
  759.                     }
  760.                 }
  761.                 $newExperience->setEndAt($endAt);
  762.                 if (isset($experience['environment_tech'])) {
  763.                     if (is_array($experience['environment_tech'])) {
  764.                         $environmentTech implode(', '$experience['environment_tech']);
  765.                     } else {
  766.                         $environmentTech $experience['environment_tech'];
  767.                     }
  768.                 } else {
  769.                     $environmentTech ''// Valeur par défaut si 'environment_tech' n'existe pas
  770.                 }
  771.                 if (isset($experience['missions'])) {
  772.                     if (is_array($experience['missions'])) {
  773.                         // Convertir le tableau en chaîne de caractères avec des sauts de ligne
  774.                         $missions implode("\n"$experience['missions']);
  775.                     } else {
  776.                         // Vérifier si 'missions' est déjà une chaîne de caractères
  777.                         $missions $experience['missions'];
  778.                     }
  779.                 } else {
  780.                     // Définir une valeur par défaut si 'missions' n'existe pas
  781.                     $missions '';
  782.                 }
  783.                 try {
  784.                     $startAt = isset($experience['start_at']) ? new \DateTime($experience['start_at']) : new \DateTime();
  785.                 } catch (\Exception $e) {
  786.                     // Utiliser une date par défaut ou gérer l'erreur
  787.                     $startAt = new \DateTime(); // Date actuelle ou une autre valeur par défaut
  788.                 }
  789.                 $newExperience->setEnvironment($environmentTech)
  790.                     ->setMissions($missions)
  791.                     ->setObjectif('')
  792.                     ->setStartAt($startAt);
  793.                 // Assurez-vous que 'title' est toujours une chaîne de caractères
  794.                 $title $experience['title'] ?? '';
  795.                 if (!is_string($title)) {
  796.                     $title '';
  797.                 }
  798.                 $newExperience->setTitle($title);
  799.                 $profile->addExperience($newExperience);
  800.             }
  801.         }
  802.         // Vérifier si la clé 'certifications' existe
  803.         if (isset($data['certifications'])) {
  804.             $certificationData $data['certifications'];
  805.         } else {
  806.             $certificationData null// Ou définir une valeur par défaut appropriée
  807.         }
  808.         if (isset($data['anglais'])) {
  809.             $anglais $data['anglais'];
  810.             // Mapper des valeurs possibles aux niveaux de la classe
  811.             $levelMapping = [
  812.                 'notions' => EnglishLevel::NOTION,
  813.                 'technique' => EnglishLevel::TECHNIQUE,
  814.                 'courant' => EnglishLevel::COURANT,
  815.             ];
  816.             $englishLevel $levelMapping[strtolower($anglais)] ?? EnglishLevel::NOTION;  // Niveau par défaut
  817.             // dd($englishLevel);
  818.             $profile->setEnglishLevel($englishLevel);
  819.         }
  820.         if (!empty($certificationData)) {
  821.             foreach ($certificationData as $certification) {
  822.                 $newCertification = new Certification();
  823.                 $newCertification->setTitle($certification['title'] ?? '')
  824.                     ->setEtablissement($certification['etablissement'] ?? '');
  825.                 // Vérification et conversion de l'année d'obtention
  826.                 if (isset($certification['obtention_year']) && is_numeric($certification['obtention_year'])) {
  827.                     $obtentionYear = (int)$certification['obtention_year'];
  828.                     error_log('Obtention Year: ' $obtentionYear);
  829.                     $newCertification->setObtentionYear($obtentionYear);
  830.                 } else {
  831.                     // Définir une valeur par défaut appropriée ou gérer l'erreur
  832.                     error_log('Invalid Obtention Year: ' . (isset($certification['obtention_year']) ? $certification['obtention_year'] : 'not set'));
  833.                     $newCertification->setObtentionYear(0);
  834.                 }
  835.                 $profile->addCertification($newCertification);
  836.             }
  837.         }
  838.         // Vérifier si la clé 'certifications' existe
  839.         if (isset($data['présentation'])) {
  840.             $presentationData $data['présentation'];
  841.         } else {
  842.             $presentationData null// Ou définir une valeur par défaut appropriée
  843.         }
  844.         if (!empty($presentationData)) {
  845.             $profile->setAbout($presentationData);
  846.         }
  847.         if (isset($data['url_Linkedin'])) {
  848.             $linkedInData $data['url_Linkedin'];
  849.         } else {
  850.             $linkedInData null// Ou définir une valeur par défaut appropriée
  851.         }
  852.         if (!empty($linkedInData)) {
  853.             $profile->setLinkedin($linkedInData);
  854.         }
  855.         $profile->setFinished(false);
  856.         $profile->setProfileType(0);
  857.         // dump($jsonData);
  858.         // dd($profile);
  859.         $entityManager->flush();
  860.         if ($isIntercontrat === 0) {
  861.             if (empty($user->getFirstname())) {
  862.                 $user->setFirstname($profile->getFirstname());
  863.                 $entityManager->persist($user);
  864.             }
  865.             if (empty($user->getLastname())) {
  866.                 $user->setLastname($profile->getName());
  867.                 $entityManager->persist($user);
  868.             }
  869.         }
  870.         $profile->updateSlug();
  871.         // Étape 1 : Enregistrement du profil
  872.         $entityManager->persist($profile);
  873.         $entityManager->flush(); // À ce stade, $profile->getId() contient l'ID généré
  874.         // Étape 2 : Chemin du fichier JSON
  875.         $jsonFilePath $this->getParameter('cv_status_directory') . '/' $id_data '.json';
  876.         // Étape 3 : Charger le contenu JSON
  877.         $data json_decode(file_get_contents($jsonFilePath), true);
  878.         // Étape 4 : Ajouter l’ID du profil
  879.         $data['profile_id'] = $profile->getId();
  880.         // Étape 5 : Écrire le JSON mis à jour dans le fichier
  881.         file_put_contents($jsonFilePathjson_encode($dataJSON_PRETTY_PRINT JSON_UNESCAPED_UNICODE));
  882.         if ($isIntercontrat === 1) {
  883.             return $this->redirectToRoute('profile_list', [], Response::HTTP_SEE_OTHER);
  884.         } else {
  885.             if ($id_user !== null) {
  886.                 // suppression du fichier $uniqueId.json
  887.                 // unlink($this->getParameter('cv_status_directory') . '/' . $id_data . '.json');
  888.                 return $this->json(['status' => 'success''message' => 'Profil créé avec succès'], Response::HTTP_OK);
  889.             } else {
  890.                 return $this->redirectToRoute('complete_first_edit', [], Response::HTTP_SEE_OTHER);
  891.             }
  892.         }
  893.     }
  894.     /**
  895.      * @Route("/complete_first_edit", name="complete_first_edit", methods={"GET", "POST"})
  896.      */
  897.     public function completeResumeFirstEdit(
  898.         Request                $request,
  899.         EntityManagerInterface $entityManager,
  900.         PDFUploader            $pdfUploader,
  901.         AvatarUploader         $avatarUploader,
  902.         SessionInterface       $session
  903.     ): Response {
  904.         /* @var User $user */
  905.         $user $this->getUser();
  906.         $profile $user->getUniqueProfile();
  907.         if (!preg_match('/^(https?:\/\/)?([a-z]{2,3}\.)?linkedin\.com\/in\/[a-zA-Z0-9%\-]+\/?$/'$profile->getLinkedin())) {
  908.             $profile->setLinkedin(null);
  909.         }
  910.         // dd($profile);
  911.         if ($profile->getLocation() == 'N/A') {
  912.             $profile->setLocation('');
  913.         }
  914.         if ($profile->getFirstname() == 'N/A' || $profile->getFirstname() == 'Anonyme') {
  915.             $profile->setFirstname('');
  916.         }
  917.         if ($profile->getName() == 'N/A' || $profile->getName() == 'Anonyme') {
  918.             $profile->setName('');
  919.         }
  920.         if ($profile->getTitle() == 'N/A') {
  921.             $profile->setTitle('');
  922.         }
  923.         $profile->setMobility([]);
  924.         $isNew true;
  925.         $cv_file $profile->getCvFile();
  926.         $originalSkills = new ArrayCollection();
  927.         $originalExperiences = new ArrayCollection();
  928.         $originalDiplomes = new ArrayCollection();
  929.         $originalCertifications = new ArrayCollection();
  930.         foreach ($profile->getSkills() as $skill) {
  931.             $originalSkills->add($skill);
  932.         }
  933.         // dd($profile);
  934.         // foreach ($profile->getExperiences() as $experience) {
  935.         //     $originalExperiences->add($experience);
  936.         // }
  937.         //
  938.         // foreach ($profile->getDiplomes() as $diplome) {
  939.         //     $originalDiplomes->add($diplome);
  940.         // }
  941.         //
  942.         // foreach ($profile->getCertifications() as $certification) {
  943.         //     $originalCertifications->add($certification);
  944.         // }
  945.         $form $this->createForm(ProfileFormType::class, $profile, ['isNew' => $isNew]);
  946.         $form->handleRequest($request);
  947.         if ($form->isSubmitted() && $form->isValid()) {
  948.             // $contrats = $form->get('contrats')->getData(); // Cela renvoie un tableau
  949.             $profile->setCvFile($cv_file);
  950.             // dd($profile);
  951.             $session->remove('generated_content');
  952.             if (!$profile->getId()) {
  953.                 $entityManager->persist($profile);
  954.             }
  955.             foreach ($originalSkills as $skill) {
  956.                 if (false === $profile->getSkills()->contains($skill)) {
  957.                     $entityManager->remove($skill);
  958.                 }
  959.             }
  960.             // foreach ($originalExperiences as $experience) {
  961.             //     if (false === $profile->getExperiences()->contains($experience)) {
  962.             //         $entityManager->remove($experience);
  963.             //     }
  964.             // }
  965.             //
  966.             // foreach ($originalDiplomes as $diplome) {
  967.             //     if (false === $profile->getDiplomes()->contains($diplome)) {
  968.             //         $entityManager->remove($diplome);
  969.             //     }
  970.             // }
  971.             //
  972.             // foreach ($originalCertifications as $certification) {
  973.             //     if (false === $profile->getCertifications()->contains($certification)) {
  974.             //         $entityManager->remove($certification);
  975.             //     }
  976.             // }
  977.             foreach ($profile->getSkills() as $skill) {
  978.                 $skill->setProfile($profile);
  979.                 $entityManager->persist($skill);
  980.             }
  981.             // foreach ($profile->getExperiences() as $experience) {
  982.             //     $experience->setProfile($profile);
  983.             //     $entityManager->persist($experience);
  984.             // }
  985.             //
  986.             foreach ($profile->getDiplomes() as $diplome) {
  987.                 if ($diplome->getLevel() == null) {
  988.                     $diplome->setLevel('');
  989.                 }
  990.                 if ($diplome->getUniversity() == null) {
  991.                     $diplome->setUniversity('');
  992.                 }
  993.                 $diplome->setProfile($profile);
  994.                 $entityManager->persist($diplome);
  995.             }
  996.             //
  997.             // foreach ($profile->getCertifications() as $certification) {
  998.             //     $certification->setProfile($profile);
  999.             //     $entityManager->persist($certification);
  1000.             // }
  1001.             if (!empty($user->getPhoto())) {
  1002.                 $profile->setPhoto($user->getPhoto());
  1003.                 $pdfFile $form->get('cv_file')->getData();
  1004.                 if (isset($pdfFile) && is_object($pdfFile)) {
  1005.                     $pdfSavedFile $pdfUploader->upload($pdfFile);
  1006.                     if ($pdfSavedFile) {
  1007.                         $profile->setCvname($pdfSavedFile['name']);
  1008.                         $profile->setCvFile($pdfSavedFile['path']);
  1009.                     }
  1010.                 }
  1011.             } else {
  1012.                 $this->handleUpload($profile$form$pdfUploader$avatarUploader);
  1013.             }
  1014.             $profile->setFinished(true);
  1015.             if ($user->isFreelance() && empty($user->getPhoto())) {
  1016.                 $user->setPhoto($profile->getPhoto());
  1017.             }
  1018.             if (!empty($profileForm['name'])) {
  1019.                 $user->setLastname($profileForm['name']);
  1020.             }
  1021.             if (!empty($profileForm['firstname'])) {
  1022.                 $user->setFirstname($profileForm['firstname']);
  1023.             }
  1024.             if (!empty($profileForm['civility'])) {
  1025.                 $user->setCivility($profileForm['civility']);
  1026.             }
  1027.             // dd($profile);
  1028.             $entityManager->flush();
  1029.             $profile->updateSlug();
  1030.             $entityManager->persist($profile);
  1031.             $entityManager->flush();
  1032.             $this->addFlash('success''Profil mis à jour');
  1033.             return $this->redirectToRoute('edit_talent_profile', [], Response::HTTP_SEE_OTHER);
  1034.         }
  1035.         return $this->render('profile/completeResume.html.twig', [
  1036.             'modalEnreg' => false,
  1037.             'profile' => $profile,
  1038.             'form' => $form->createView(),
  1039.             'isIntercontrat' => false,
  1040.             'regionjson' => json_encode(FrenchRegion::REGION_DEPARTEMENTJSON_UNESCAPED_UNICODE),
  1041.         ]);
  1042.     }
  1043.     /**
  1044.      * @Route("/complete", name="complete_resume_profile", methods={"GET", "POST"})
  1045.      */
  1046.     public function completeResume(
  1047.         Request                $request,
  1048.         EntityManagerInterface $entityManager,
  1049.         PDFUploader            $pdfUploader,
  1050.         AvatarUploader         $avatarUploader,
  1051.         SessionInterface       $session
  1052.     ): Response {
  1053.         /* @var User $user */
  1054.         $user $this->getUser();
  1055.         $profile $user->getUniqueProfile();
  1056.         // REDIRECT IF COMPLETE
  1057.         if ($profile->getTitle()) {
  1058.             return $this->redirectToRoute("edit_talent_profile");
  1059.         }
  1060.         $profile->setIsVisible(true);
  1061.         $isNew false;
  1062.         if (!$profile->getId()) {
  1063.             $isNew true;
  1064.             $profile->setUrl($profile->getName());
  1065.         }
  1066.         $profileForm $request->get('profile_form');
  1067.         $originalSkills = new ArrayCollection();
  1068.         $originalExperiences = new ArrayCollection();
  1069.         $originalDiplomes = new ArrayCollection();
  1070.         $originalCertifications = new ArrayCollection();
  1071.         foreach ($profile->getSkills() as $skill) {
  1072.             $originalSkills->add($skill);
  1073.         }
  1074.         foreach ($profile->getExperiences() as $experience) {
  1075.             $originalExperiences->add($experience);
  1076.         }
  1077.         foreach ($profile->getDiplomes() as $diplome) {
  1078.             $originalDiplomes->add($diplome);
  1079.         }
  1080.         foreach ($profile->getCertifications() as $certification) {
  1081.             $originalCertifications->add($certification);
  1082.         }
  1083.         $form $this->createForm(ProfileFormType::class, $profile, ['isNew' => $isNew]);
  1084.         $form->handleRequest($request);
  1085.         // if ($form->isSubmitted() && $form->isValid()) {
  1086.         //
  1087.         //
  1088.         //     // dd($profile);
  1089.         //     $session->remove('generated_content');
  1090.         //
  1091.         //
  1092.         //     if (!$profile->getId()) {
  1093.         //         $entityManager->persist($profile);
  1094.         //     }
  1095.         //
  1096.         //     foreach ($originalSkills as $skill) {
  1097.         //         if (false === $profile->getSkills()->contains($skill)) {
  1098.         //             $entityManager->remove($skill);
  1099.         //         }
  1100.         //     }
  1101.         //
  1102.         //     foreach ($originalExperiences as $experience) {
  1103.         //         if (false === $profile->getExperiences()->contains($experience)) {
  1104.         //             $entityManager->remove($experience);
  1105.         //         }
  1106.         //     }
  1107.         //
  1108.         //     foreach ($originalDiplomes as $diplome) {
  1109.         //         if (false === $profile->getDiplomes()->contains($diplome)) {
  1110.         //             $entityManager->remove($diplome);
  1111.         //         }
  1112.         //     }
  1113.         //
  1114.         //     foreach ($originalCertifications as $certification) {
  1115.         //         if (false === $profile->getCertifications()->contains($certification)) {
  1116.         //             $entityManager->remove($certification);
  1117.         //         }
  1118.         //     }
  1119.         //
  1120.         //     foreach ($profile->getSkills() as $skill) {
  1121.         //         $skill->setProfile($profile);
  1122.         //         $entityManager->persist($skill);
  1123.         //     }
  1124.         //
  1125.         //     foreach ($profile->getExperiences() as $experience) {
  1126.         //         $experience->setProfile($profile);
  1127.         //         $entityManager->persist($experience);
  1128.         //     }
  1129.         //
  1130.         //     foreach ($profile->getDiplomes() as $diplome) {
  1131.         //         $diplome->setProfile($profile);
  1132.         //         $entityManager->persist($diplome);
  1133.         //     }
  1134.         //
  1135.         //     foreach ($profile->getCertifications() as $certification) {
  1136.         //         $certification->setProfile($profile);
  1137.         //         $entityManager->persist($certification);
  1138.         //     }
  1139.         //
  1140.         //     if (!empty($user->getPhoto())) {
  1141.         //         $profile->setPhoto($user->getPhoto());
  1142.         //     } else {
  1143.         //         $this->handleUpload($profile, $form, $pdfUploader, $avatarUploader);
  1144.         //     }
  1145.         //
  1146.         //
  1147.         //     if ($user->isFreelance() && empty($user->getPhoto())) {
  1148.         //         $user->setPhoto($profile->getPhoto());
  1149.         //     }
  1150.         //
  1151.         //     if (!empty($profileForm['name'])) {
  1152.         //         $user->setLastname($profileForm['name']);
  1153.         //     }
  1154.         //     if (!empty($profileForm['firstname'])) {
  1155.         //         $user->setFirstname($profileForm['firstname']);
  1156.         //     }
  1157.         //     if (!empty($profileForm['civility'])) {
  1158.         //         $user->setCivility($profileForm['civility']);
  1159.         //     }
  1160.         //
  1161.         //     $entityManager->flush();
  1162.         //
  1163.         //     $profile->updateSlug();
  1164.         //     $entityManager->persist($profile);
  1165.         //     $entityManager->flush();
  1166.         //
  1167.         //     $this->addFlash('success', 'Profil mis à jour');
  1168.         //     return $this->redirectToRoute('edit_talent_profile', [], Response::HTTP_SEE_OTHER);
  1169.         // }
  1170.         return $this->render('profile/completeResumeBefore.html.twig', [
  1171.             'modalEnreg' => false,
  1172.             'profile' => $profile,
  1173.             'form' => $form->createView(),
  1174.             'isIntercontrat' => false,
  1175.             'regionjson' => json_encode(FrenchRegion::REGION_DEPARTEMENTJSON_UNESCAPED_UNICODE),
  1176.         ]);
  1177.     }
  1178.     /**
  1179.      * @Route("/{id}", name="profile_show", methods={"GET"})
  1180.      * @param Profile $profile
  1181.      * @return Response
  1182.      */
  1183.     public function show(Profile $profile): Response
  1184.     {
  1185.         return $this->render('profile/show.html.twig', [
  1186.             'profile' => $profile,
  1187.         ]);
  1188.     }
  1189.     /**
  1190.      * @Route("/intercontrat_une", name="intercontrat_highlight", methods={"POST"})
  1191.      */
  1192.     public function intercontratHighlight(
  1193.         Request                $request,
  1194.         ProfileRepository      $profileRepository,
  1195.         EntityManagerInterface $entityManager
  1196.     ) {
  1197.         /* @var User $user */
  1198.         $user $this->getUser();
  1199.         $profile $profileRepository->find($request->get('id'));
  1200.         if ($profile) {
  1201.             $intercontratUne abs((int)$user->getSociety()->getIntercontratUne() - (int)$profileRepository->countIntercontratUne($user));
  1202.             $isHighlight $request->get('isHighlight');
  1203.             if ($intercontratUne && $isHighlight) {
  1204.                 return new JsonResponse(['error' => 'Vous avez dépassez le nombre de contrat en une']);
  1205.             }
  1206.             $profile->setIsHighlight($isHighlight);
  1207.             $entityManager->flush();
  1208.         }
  1209.         return new JsonResponse(['success' => true]);
  1210.     }
  1211.     /**
  1212.      * @Route("/{id}/edit/{first}", name="profile_edit", methods={"GET", "POST"}, defaults={"first"=0})
  1213.      * @param Request $request
  1214.      * @param Profile $profile
  1215.      * @param int first
  1216.      * @param ProfileRepository $profileRepository
  1217.      * @param EntityManagerInterface $entityManager
  1218.      * @param PDFUploader $pdfUploader
  1219.      * @param AvatarUploader $avatarUploader
  1220.      * @return Response
  1221.      */
  1222.     public function edit(
  1223.         Request                $request,
  1224.         Profile                $profile,
  1225.         int                    $first 0,
  1226.         ProfileRepository      $profileRepository,
  1227.         EntityManagerInterface $entityManager,
  1228.         PDFUploader            $pdfUploader,
  1229.         AvatarUploader         $avatarUploader
  1230.     ): Response {
  1231.         /* @var User $user */
  1232.         $user $this->getUser();
  1233.         /**
  1234.          *   ACCESS SOCIETY
  1235.          */
  1236.         if ($profile->getUser() !== $user) {
  1237.             if ($profile->getUserRecruteur()) {
  1238.                 if ($profile->getUserRecruteur() !== $user) {
  1239.                     return $this->redirectToRoute('app_exception');
  1240.                 }
  1241.             } else {
  1242.                 return $this->redirectToRoute('app_exception');
  1243.             }
  1244.         }
  1245.         $intercontratUne abs((int)$user->getSociety()->getIntercontratUne() - (int)$profileRepository->countIntercontratUne($user));
  1246.         $originalSkills = new ArrayCollection();
  1247.         $originalExperiences = new ArrayCollection();
  1248.         $originalDiplomes = new ArrayCollection();
  1249.         $originalCertifications = new ArrayCollection();
  1250.         foreach ($profile->getSkills() as $skill) {
  1251.             $originalSkills->add($skill);
  1252.         }
  1253.         foreach ($profile->getExperiences() as $experience) {
  1254.             $originalExperiences->add($experience);
  1255.         }
  1256.         foreach ($profile->getDiplomes() as $diplome) {
  1257.             $originalDiplomes->add($diplome);
  1258.         }
  1259.         foreach ($profile->getCertifications() as $certification) {
  1260.             $originalCertifications->add($certification);
  1261.         }
  1262.         $form $this->createForm(ProfileFormType::class, $profile, ['isNew' => false]);
  1263.         $form->handleRequest($request);
  1264.         if ($form->isSubmitted() && $form->isValid()) {
  1265.             $profile->setIsHighlight($request->get('isHighlight'false));
  1266.             if (!$profile->getId()) {
  1267.                 $entityManager->persist($profile);
  1268.             }
  1269.             foreach ($originalSkills as $skill) {
  1270.                 if (false === $profile->getSkills()->contains($skill)) {
  1271.                     $entityManager->remove($skill);
  1272.                 }
  1273.             }
  1274.             foreach ($originalExperiences as $experience) {
  1275.                 if (false === $profile->getExperiences()->contains($experience)) {
  1276.                     $entityManager->remove($experience);
  1277.                 }
  1278.             }
  1279.             foreach ($originalDiplomes as $diplome) {
  1280.                 if (false === $profile->getDiplomes()->contains($diplome)) {
  1281.                     $entityManager->remove($diplome);
  1282.                 }
  1283.             }
  1284.             foreach ($originalCertifications as $certification) {
  1285.                 if (false === $profile->getCertifications()->contains($certification)) {
  1286.                     $entityManager->remove($certification);
  1287.                 }
  1288.             }
  1289.             foreach ($profile->getSkills() as $skill) {
  1290.                 $skill->setProfile($profile);
  1291.                 $entityManager->persist($skill);
  1292.             }
  1293.             foreach ($profile->getExperiences() as $experience) {
  1294.                 $experience->setProfile($profile);
  1295.                 $entityManager->persist($experience);
  1296.             }
  1297.             foreach ($profile->getDiplomes() as $diplome) {
  1298.                 $diplome->setProfile($profile);
  1299.                 $entityManager->persist($diplome);
  1300.             }
  1301.             foreach ($profile->getCertifications() as $certification) {
  1302.                 $certification->setProfile($profile);
  1303.                 $entityManager->persist($certification);
  1304.             }
  1305.             $this->handleUpload($profile$form$pdfUploader$avatarUploader);
  1306.             $user $profile->getUser();
  1307.             if ($user->isFreelance()) {
  1308.                 $user->setPhoto($profile->getPhoto());
  1309.             }
  1310.             $entityManager->flush();
  1311.             return $this->redirectToRoute('profile_list', [], Response::HTTP_SEE_OTHER);
  1312.         }
  1313.         return $this->renderForm('profile/edit.html.twig', [
  1314.             'modalEnreg' => $first === 1,
  1315.             'profile' => $profile,
  1316.             'form' => $form,
  1317.             'isIntercontrat' => true,
  1318.             'intercontratUne' => $intercontratUne,
  1319.             'regionjson' => json_encode(FrenchRegion::REGION_DEPARTEMENTJSON_UNESCAPED_UNICODE),
  1320.         ]);
  1321.     }
  1322.     /**
  1323.      * @Route("/{id}", name="profile_delete", methods={"POST"})
  1324.      */
  1325.     public function delete(Request $requestProfile $profileEntityManagerInterface $entityManager): Response
  1326.     {
  1327.         /* @var User $user */
  1328.         $user $this->getUser();
  1329.         /**
  1330.          *   ACCESS SOCIETY
  1331.          */
  1332.         if ($profile->getUser() !== $user) {
  1333.             if ($profile->getUserRecruteur()) {
  1334.                 if ($profile->getUserRecruteur() !== $user) {
  1335.                     return $this->redirectToRoute('app_exception');
  1336.                 }
  1337.             } else {
  1338.                 return $this->redirectToRoute('app_exception');
  1339.             }
  1340.         }
  1341.         if ($this->isCsrfTokenValid('delete' $profile->getId(), $request->request->get('_token'))) {
  1342.             $entityManager->remove($profile);
  1343.             $entityManager->flush();
  1344.         }
  1345.         return $this->redirectToRoute('profile_list', [], Response::HTTP_SEE_OTHER);
  1346.     }
  1347.     /**
  1348.      * @Route("/changer/disponibilité", name="profile_edit_disponibility", methods={"GET"})
  1349.      * @IsGranted("ROLE_FREELANCE")
  1350.      */
  1351.     public function editDisponibility(
  1352.         Request                $request,
  1353.         EntityManagerInterface $entityManager
  1354.     ): Response {
  1355.         $disponibility $request->query->get("disponibility");
  1356.         $listDisponibility = [
  1357.             'Immédiate',
  1358.             'Sous 1 mois',
  1359.             'Sous 2 mois',
  1360.             'Sous 3 mois',
  1361.         ];
  1362.         if ($disponibility && in_array($disponibility$listDisponibility)) {
  1363.             /** @var User $currentUser */
  1364.             $currentUser $this->getUser();
  1365.             $profileUser $currentUser->getUniqueProfile();
  1366.             $profileUser->setDisponibility($disponibility);
  1367.             $entityManager->persist($profileUser);
  1368.             $entityManager->flush();
  1369.         }
  1370.         return $this->redirect($request->headers->get('referer'));
  1371.     }
  1372. }