<?php
namespace App\Controller;
use App\Entity\Application;
use App\Entity\Attachments;
use App\Entity\Commitment;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use App\Entity\BookCv;
use App\Entity\Offer;
use App\Entity\Training;
use App\Entity\User;
use App\Form\OfferType;
use App\Manager\SendInBlue;
use App\Entity\HistoryOffers;
use App\Form\SendEmailOfferType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use SendinBlue\Client\Configuration;
use App\Entity\HistoryUser;
class OfferController extends AbstractController
{
private EntityManagerInterface $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
#[Route('/offre/voir/{id}', name: 'offer_show_user')]
public function show(Request $request, Offer $offer, $id): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('home');
}
$user = $this->entityManager->getRepository(User::class)->find($this->getUser());
$offerId = $this->entityManager->getRepository(Offer::class)->findOneBy(['id' => $id]);
if ($offerId == null) {
return $this->redirectToRoute('home');
}
// On vérifie si le candidat a déjà candidaté à cette offre
$applicationCheck = $this->entityManager->getRepository(Application::class)->findOneBy(
['user' => $user, 'offer' => $offer]
);
if (!$applicationCheck) {
$form = $this->createFormBuilder()
->add('apply', SubmitType::class, [
'label' => 'Je candidate'
])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// La candidature se fait ici
$application = new Application();
$application->setUser($user);
$application->setOffer($offer);
$cvAttachment = $this->entityManager->getRepository(Attachments::class)->findBy(
['User' => $this->getUser(), 'type' => 'cv'],
['id' => 'DESC']
);
$cv = "";
foreach ($cvAttachment as $attachment) {
if ($attachment->getAttachmentState()->getId() == 3) {
$cv = $attachment->getPath();
} else {
$this->addFlash('danger', 'Vous devez avoir envoyé votre CV pour postuler à une offre.');
return $this->redirectToRoute('search_company');
}
}
$fullName = $user->getLastname() . " " . $user->getFirstname();
$application->setCvLink($cv);
$application->setDate(new \DateTime());
// Envoi du mail à l'entreprise
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$url = $baseurl . '/uploads/cv/' . $cv;
$history = new HistoryOffers();
$history->setMember(null);
$history->setCreatedAt(new \DateTimeImmutable());
$history->setOffer($offer);
$history->setText("Le candidat " . $fullName . " à postulé a l'offre");
$this->entityManager->persist($history);
// history User
$history_user = new HistoryUser();
$history_user->setUser($user);
$history_user->setDescription(
'Candidature pour l\'offre :' . $offer->getJobTitle() . " - " . $offer->getCompanyName()
);
$history_user->setCreatedAt(new \DateTimeImmutable());
$this->entityManager->persist($history_user);
$this->entityManager->persist($application);
$this->entityManager->flush();
return $this->redirectToRoute('search_company');
}
return $this->render('user/company/show.html.twig', [
'form' => $form->createView(),
'offer' => $offer,
]);
} else {
return $this->render('user/company/show.html.twig', [
'offer' => $offer
]);
}
}
#[Route('/book-cv/{id}', name: 'book_cv')]
public function bookCV(Offer $offer, EntityManagerInterface $entityManager)
{
$bookCvs = $entityManager->getRepository(BookCv::class)->getBookCvs($offer);
return $this->render('user/company/book-cv.html.twig', [
'bookCvs' => $bookCvs,
'offer' => $offer,
]);
}
#[Route('/book-cv/{title}/{id}', name: 'book_cv_public')]
public function bookCVBis(Offer $offer, $title, EntityManagerInterface $entityManager)
{
$bookCvs = $entityManager->getRepository(BookCv::class)->getBookCvs($offer);
return $this->render('user/company/book-cv.html.twig', [
'bookCvs' => $bookCvs,
'offer' => $offer,
]);
}
#[Route('/offre/ajouter', name: 'offer_add')]
public function add(Request $request, SendInBlue $sendInBlue, EntityManagerInterface $em)
{
$offer = new Offer();
$trainings = $em->getRepository(Training::class)->findBy(['enabled' => 1], ['levelName' => 'DESC']);
$form = $this->createForm(OfferType::class, $offer);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$trainingRequest = $request->request->all("trainings");
if ($request->request->get('recaptchaResponse') && $request->request->get('recaptchaResponse') != null) {
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'; // URL to the reCAPTCHA server
$recaptcha_secret = '6Lf982YpAAAAADyzWvftfXuFWHEJHPUHbqmSs54D'; // Secret key
$recaptcha_response = $request->request->get('recaptchaResponse'); // Response from reCAPTCHA server, added to the form during processing
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response); // Send request to the server
$recaptcha = json_decode($recaptcha); // Decode the JSON response
if ($recaptcha->success == false || $recaptcha->action != "submit") { // If the response is valid
$this->addFlash('error', 'Votre demande n\'a pas pu être envoyée, veuillez réessayer.');
return $this->redirectToRoute("offer_add");
} elseif ($recaptcha->score <= 0.5) {
$this->addFlash('error', 'Votre demande n\'a pas pu être envoyée, veuillez réessayer.');
return $this->redirectToRoute("offer_add");
}
} else {
$this->addFlash('error', 'Votre demande n\'a pas pu être envoyée, veuillez réessayer.');
return $this->redirectToRoute("offer_add");
}
foreach ($trainingRequest as $tr) {
$training = $em->getRepository(Training::class)->findOneBy(['id' => $tr]);
$offer->addTraining($training);
}
$offer->setDate(new \DateTime());
$jobDescription = $form->get('job_description')->getData();
$newDescr = trim(preg_replace('/\r\n+/', '<br>', $jobDescription));
$offer->setCompany(true);
$offer->setState(false);
$offer->setJobDescription($newDescr);
$em->persist($offer);
$em->flush();
$history = new HistoryOffers();
$history->setMember(null);
$history->setCreatedAt(new \DateTimeImmutable());
$history->setOffer($offer);
$history->setText("Création de l'offre -- via formulaire pour entreprises");
$em->persist($history);
$em->flush();
$email = "maxime.diho@INTERFOR-SIA.COM";
if ($_ENV['APP_ENV'] == 'dev') {
$email = "alice@awelty.com";
}
$payload = [
'to' => [
['email' => $email]
],
'templateId' => $sendInBlue->getTemplateId('offer_commercial'),
'params' => [
'url_button' =>
$this->getParameter('url') .
$this->generateUrl(
'admin_offer_show',
['id' => $offer->getId()]
),
]
];
$sendInBlue->sendMail($payload);
$payload = [
'to' => [
['email' => $email]
],
'templateId' => $sendInBlue->getTemplateId('offer_send_to_company'),
];
$sendInBlue->sendMail($payload);
$this->addFlash(
'success',
'Merci d\'avoir publié une offre,
celle-ci sera validée par Interfor avant d\'être visible par les candidats.'
);
return $this->redirectToRoute('company');
}
return $this->render('company/offer_add.html.twig', [
'form' => $form->createView(),
'trainings' => $trainings
]);
}
#[Route('/company/renvoi-d-offres', name: 'company_send_mail')]
public function sendOffers(Request $request, SendInBlue $sendInBlue, EntityManagerInterface $em)
{
$form = $this->createForm(SendEmailOfferType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
/*url pour modifier offre d'emploi */
$company = $em->getRepository(Offer::class)->findBy(['company_email' => $data['company_email']]);
if ($company != null) {
foreach ($company as $companie) {
$url = $this->getParameter('url') . $this->generateUrl('book_cv', ['id' => $companie->getId()]);
$email = $companie->getCompanyEmail();
if ($_ENV['APP_ENV'] == 'dev') {
$email = "alice@awelty.com";
}
$payload = [
'to' => [
['email' => "alice@awelty.com"]
],
'templateId' => $sendInBlue->getTemplateId('resend_offer_to_company'),
'params' => [
'company_name' => $companie->getCompanyName(),
'offer_title' => $companie->getJobTitle(),
'url_button' => $url,
'company_address' => $this->getParameter('COMPANY_ADDRESS'),
'company_phone' => $this->getParameter('COMPANY_PHONE'),
],
'subject' => 'Vous avez demandé l\'accès à votre annonce ' . $companie->getJobTitle()
];
$sendInBlue->sendMail($payload);
}
$this->addFlash('success', 'Veuillez consulter votre boîte mail, pour accéder aux offres');
}
if (empty($company) || $company == null) {
$this->addFlash('warning', 'Vous n\'avez publié aucune offre d\'emploi.');
}
}
$history = new HistoryOffers();
$history->setMember(null);
$history->setCreatedAt(new \DateTimeImmutable());
$history->setText("L'entreprise a demandé à accéder à l'offre");
$em->persist($history);
return $this->render('company/send.html.twig', [
'form' => $form->createView(),
]);
}
#[Route('/offre/modifier/{id}', name: 'offer_edit_offer', methods: ['POST', 'GET', "PUT"])]
public function offerCompanyEdit(Request $request, $id, EntityManagerInterface $em, SendInBlue $sendInBlue)
{
$offer = $em->getRepository(Offer::class)->find($id);
$trainings = $em->getRepository(Training::class)->findBy([], ['levelName' => 'DESC']);
$form = $this->createForm(OfferType::class, $offer);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$trainingRequest = $request->request->all("trainings");
foreach ($trainingRequest as $tr) {
$training = $em->getRepository(Training::class)->findOneBy(['id' => $tr]);
$offer->addTraining($training);
}
$offer->setDate(new \DateTime());
$jobDescription = $form->get('job_description')->getData();
$newDescr = trim(preg_replace('/\r\n+/', '<br>', $jobDescription));
$offer->setJobDescription($newDescr);
$history = new HistoryOffers();
$history->setMember(null);
$history->setCreatedAt(new \DateTimeImmutable());
$history->setOffer($offer);
$history->setText("Modification de l'offre -- via formulaire pour entreprises");
$em->persist($history);
$em->persist($offer);
$em->flush();
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$payload = [
'to' => [
// ['email' => "alternance@interfor-sia.com"]
['email' => "alice@awelty.com"]
],
'templateId' => $sendInBlue->getTemplateId('offer_commercial_update'),
'params' => [
'url_button' => $baseurl . $this->generateUrl('admin_offer_show', ['id' => $offer->getId()]),
'company_address' => $this->getParameter('COMPANY_ADDRESS'),
'company_phone' => $this->getParameter('COMPANY_PHONE'),
]
];
$sendInBlue->sendMail($payload);
$this->addFlash('success', 'Modifications ont été effectuées avec succès !');
}
return $this->render('company/offer_edit.html.twig', [
'form' => $form->createView(),
'trainings' => $trainings,
'offer' => $offer,
]);
}
#[Route('/company/engagement', name: 'company_send_mail_commitment')]
public function sendOffersCommitment(Request $request, EntityManagerInterface $em)
{
$form = $this->createForm(SendEmailOfferType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$phone = $request->request->get('phone');
/*url pour modifier offre d'emploi */
$company = $em->getRepository(Commitment::class)->findOneBy(['company_email' => $data['company_email']]);
$user = $em->getRepository(User::class)->findOneBy(['phone' => $phone]);
$history = new HistoryOffers();
$history->setMember(null);
$history->setCreatedAt(new \DateTimeImmutable());
$history->setText("Entreprise -- Demande d'accès a l'engagement");
$em->persist($history);
$em->flush();
$hasCommitment = false;
if ($company) {
if ($user) {
return $this->redirectToRoute('company_commitment', [ 'id' => $company->getId()]);
} else {
$this->addFlash(
'warning',
'Nous n\'avons pas pu trouver d\'étudiant avec ce numéro de téléphone.' .
' Rapprochez-vous du service recrutement alternance@interfor-sia.com et au 03 22 82 00 70.'
);
}
} else {
$this->addFlash('warning', 'Nous n\'avons pas pu trouver d\'offre comprenant ce mail.');
}
}
return $this->render('company/sendEmailComitment.html.twig', [
'form' => $form->createView(),
]);
}
}