<?php
namespace App\Controller\Frontend;
use App\Entity\Campaign;
use App\Entity\Status;
use App\Misc\CaptchaHelper;
use App\Utilities\ServiceUtil;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use App\Exception\BadRequestException;
use Symfony\Contracts\Translation\TranslatorInterface;
use App\Annotation\Log;
use App\Constant\Common;
class ProfileController extends BaseFrontendController
{
/**
* @Route("/{_locale}/dossier-inscription/step1", name="profile.step1", methods={"GET"})
*/
public function profileStep1(TranslatorInterface $translator)
{
$siteName = $translator->trans('siteName');
$this->addTitle($translator->trans(
'profile_step1.title',
[
'%siteName%' => $siteName
]
));
$this->setDescription($translator->trans(
'profile_step1.desc',
[
'%siteName%' => $siteName
]
));
// get profile logged in
$data['formData'] = [
'errors' => [],
'inputValues' => []
];
if ($this->getUser()) {
$data['formData']['inputValues'] = $this->currentService->getProfileByUserId($this->getUser()->getId());
}
$data = array_merge($data, $this->stepData());
if (isset($data['formData']['inputValues']['year'])) {
$data['year'] = $data['formData']['inputValues']['year'];
}
return $this->render('user/profile/profile_step1.html.twig', $data);
}
/**
* @Route("/{_locale}/dossier-inscription/step2", name="profile.step2", methods={"GET"})
*/
public function profileStep2(TranslatorInterface $translator)
{
if (!$this->getUser()) {
return $this->redirectToRoute('profile.step1');
}
$siteName = $translator->trans('siteName');
$this->addTitle($translator->trans(
'profile_step1.title',
[
'%siteName%' => $siteName
]
));
$this->setDescription($translator->trans(
'profile_step1.desc',
[
'%siteName%' => $siteName
]
));
$data['formData'] = [
'errors' => [],
'inputValues' => $this->currentService->getProfileByUserId($this->getUser()->getId())
];
$data = array_merge($data, $this->stepData());
if (isset($data['formData']['inputValues']['year'])) {
$data['year'] = $data['formData']['inputValues']['year'];
}
return $this->render('user/profile/profile_step2.html.twig', $data);
}
/**
* @Route("/{_locale}/dossier-inscription/step3", name="profile.step3", methods={"GET"})
*/
public function profileStep3(TranslatorInterface $translator)
{
if (!$this->getUser()) {
return $this->redirectToRoute('profile.step1');
}
$siteName = $translator->trans('siteName');
$this->addTitle($translator->trans(
'profile_step1.title',
[
'%siteName%' => $siteName
]
));
$this->setDescription($translator->trans(
'profile_step1.desc',
[
'%siteName%' => $siteName
]
));
$data['formData'] = [
'errors' => [],
'inputValues' => $this->currentService->getProfileByUserId($this->getUser()->getId())
];
$data = array_merge($data, $this->stepData());
if (isset($data['formData']['inputValues']['year'])) {
$data['year'] = $data['formData']['inputValues']['year'];
}
return $this->render('user/profile/profile_step3.html.twig', $data);
}
/**
* @Route("/{_locale}/dossier-inscription/step4", name="profile.step4", methods={"GET"})
*/
public function profileStep4(TranslatorInterface $translator)
{
if (!$this->getUser()) {
return $this->redirectToRoute('profile.step1');
}
$siteName = $translator->trans('siteName');
$this->addTitle($translator->trans(
'profile_step1.title',
[
'%siteName%' => $siteName
]
));
$this->setDescription($translator->trans(
'profile_step1.desc',
[
'%siteName%' => $siteName
]
));
$data['formData'] = [
'errors' => [],
'inputValues' => $this->currentService->getProfileByUserId($this->getUser()->getId())
];
$data = array_merge($data, $this->stepData());
if (isset($data['formData']['inputValues']['year'])) {
$data['year'] = $data['formData']['inputValues']['year'];
}
return $this->render('user/profile/profile_step4.html.twig', $data);
}
/**
* @Route("/{_locale}/profile/step1", name="profile.step1_save", methods={"POST", "PUT"})
* @Log
*/
public function profileStep1Save(
Request $request,
CaptchaHelper $captchaHelper,
TranslatorInterface $translator
) {
// new profile
if ($request->getMethod() === 'POST') {
// Check captcha is valid
if ($this->getParameter('captcha_enabled') && !$captchaHelper->isCaptchaValid($request)) {
return $this->json(ServiceUtil::processFailed([
'errorMessage' => $translator->trans('message.captcha_is_not_valid')
]));
}
$campaign = $this->campaignRepo->findOneBy(['id' => Campaign::APPLICATION]);
if ($campaign) {
$request->request->set('campaign', $campaign->getId());
}
if(!$request->get('programs')){
$data = $this->stepData();
$data['formData'] = [
'errors' => [],
'inputValues' => $request->request->all()
];
$data['valid_programs'] = $translator->trans('message.programme_is_not_valid');
return $this->render('user/profile/profile_step1.html.twig', $data);
}
try {
$this->currentService->addProfile($request);
return $this->redirectToRoute('profile.step2', ['new_user'=> 1]);
} catch (BadRequestException $badRequestException) {
$data = $this->stepData();
$data['formData'] = [
'errors' => [],
'inputValues' => $request->request->all()
];
$error = $badRequestException->getMessages();
if ($error['entityName'] === 'User') {
foreach ($error['data'] as $field => $message) {
$data['formData']['errors']['user[' . $field . ']'] = $message;
}
}
$data['validated'] = true;
return $this->render('user/profile/profile_step1.html.twig', $data);
}
}
// update step 1 and ?? go to step 2 ?
$this->userService->updateProfileUser($request->get('user'));
$this->currentService->updateProfile($request);
return $this->redirectToRoute('profile.step2');
}
/**
* @Route("/{_locale}/profile/step2", name="profile.step2_save", methods={"PUT"})
*/
public function profileStep2Save(Request $request)
{
$this->currentService->updateProfile($request, 'App\DTO\Profile\UpdateProfileStep2Input');
return $this->redirectToRoute('profile.step3');
}
/**
* @Route("/{_locale}/profile/step3", name="profile.step3_save", methods={"PUT"})
*/
public function profileStep3Save(Request $request)
{
$this->currentService->updateProfile($request, 'App\DTO\Profile\UpdateProfileStep3Input');
return $this->redirectToRoute('profile.step4');
}
/**
* @Route("/{_locale}/profile/step4", name="profile.step4_save", methods={"PUT"})
*/
public function profileStep4Save(Request $request)
{
$isSent = $request->get('isSent');
$this->userService->updateProfileUser($request->files->get('user'));
$request->files->remove('user');
$profile = $this->currentService->updateProfile($request, 'App\DTO\Profile\UpdateProfileStep4Input', true);
$param = [];
if(!$isSent){
$param = ['new_user'=> 1];
//send email to admin campus
if(isset(Common::listEmailAdmission()[$profile->getCampus1()->getId()])){
$this->userService->sendCampusEmail($profile, Common::listEmailAdmission()[$profile->getCampus1()->getId()]);
}
}
return $this->redirectToRoute('user.application', $param);
}
public function stepData()
{
$data = [];
$data['studyLevels'] = $this->studyLevelRepository->findAll();
$data['cursuses'] = $this->cursusRepository->findAll();
$data['programsByLevel'] = $this->programService->getActiveProgramGroupByLevel();
$france = $this->countryRepo->find(1);
$data['countries'] = array_merge([$france], $this->countryRepo->getAll(['except_id' => 1, 'sort_asc' => 'name'], 'ENTITY'));
$data['departments'] = array_map(function ($department) {
return ['value' => $department, 'text' => $department];
}, $this->commonService->frenchDepartments);
$data['campuses'] = $this->campusRepository->getAll(['filter_status' => 1, 'memberOf_programs' => 'notNull','sort_asc' => 'ordering'], 'ENTITY');
$year = date("Y");
if (date("Y-m-d") > date("Y") . '-10-01') {
$data['year'] = date('Y', strtotime('+1 year')) . '-' . date('Y', strtotime('+2 year'));
} else {
$data['year'] = $year . '-' . date('Y', strtotime('+1 year'));
}
return $data;
}
/**
* @Route("/{_locale}/fiche-de-renseigenement-alternance", name="fiche_de_renseigenement", methods={"GET"})
*/
public function ficheDeRenseigenement(Request $request)
{
$token = $request->get('token');
if (!$token) {
return $this->render('pages/404.html.twig');
}
$tokenStorage = explode('_MpTKRipu85cN', $token);
if (is_array($tokenStorage)) {
$profile = $this->profileRepo->find(base64_decode($tokenStorage[0]));
} else {
return $this->render('pages/404.html.twig');
}
$data = [];
$data['profile'] = $this->currentService->autoMapper->map($profile, 'App\DTO\Profile\ProfileOutput');
// dd($data['profile']);
$data['session'] = (int) $profile->getYear() ? explode('-', $profile->getYear())[0] : null;
$data['contractTypes'] = Common::contractTypes();
$data['specificPrivate'] = Common::CONTRACT_SPECIFIC_TYPES;
$data['specificPublic'] = Common::CONTRACT_SPECIFIC_PUBLIC_TYPES;
$data['employers'] = Common::CONTRACT_SPECIFIC_EMPLOYERS;
//set default list specifics
$data['specifics'] = Common::CONTRACT_SPECIFIC_TYPES;
if (isset($data['profile']->entreprise['entreprise']['type']) && $data['profile']->entreprise['entreprise']['type'] == 2) {
$data['specifics'] = Common::CONTRACT_SPECIFIC_PUBLIC_TYPES;
}
$data['sendMail'] = 0;
if ($request->get('mode') == 'public') {
$data['sendMail'] = 1;
}
return $this->render('fiche/index.html.twig', $data);
}
/**
* @Route("/{_locale}/fiche-save", name="fiche.save", methods={"PUT"})
*/
public function ficheSave(Request $request)
{
$contract = $request->get('contract');
if ($contract) {
$fullSupport = 0;
$annualCompanyTotal = 0;
if (isset($contract['contract']['annualSupport1'])) {
if ($contract['contract']['annualSupport1']) {
$fullSupport = $fullSupport + $contract['contract']['annualSupport1'];
}
if ($contract['contract']['annualCompany1']) {
$annualCompanyTotal = $annualCompanyTotal + $contract['contract']['annualCompany1'];
}
}
if (isset($contract['contract']['annualSupport2'])) {
if ($contract['contract']['annualSupport2']) {
$fullSupport = $fullSupport + $contract['contract']['annualSupport2'];
}
if ($contract['contract']['annualCompany2']) {
$annualCompanyTotal = $annualCompanyTotal + $contract['contract']['annualCompany2'];
}
}
if (isset($contract['contract']['annualSupport3'])) {
if ($contract['contract']['annualSupport3']) {
$fullSupport = $fullSupport + $contract['contract']['annualSupport3'];
}
if ($contract['contract']['annualCompany3']) {
$annualCompanyTotal = $annualCompanyTotal + $contract['contract']['annualCompany3'];
}
}
$contract['contract']['fullSupport'] = $fullSupport;
$contract['contract']['annualCompanyTotal'] = $annualCompanyTotal;
$contract['contract']['totalTrainingCost'] = $fullSupport + $annualCompanyTotal;
}
$conditions = $request->get('entreprise');
$trainingHours = 0;
if ($conditions) {
if (isset($conditions['contract']['conditions'])) {
foreach ($conditions['contract']['conditions'] as $condition) {
$trainingHours = $trainingHours + $condition['hour'];
}
}
$contract['contract']['trainingHours'] = $trainingHours;
}
$request->request->set('contract', $contract);
$profile = $this->currentService->updateProfile($request, 'App\DTO\Profile\UpdateProfileFicheInput');
if ($request->get('sendMail')) {
$this->userService->sendFicheEmail($this->currentService->autoMapper->map($profile, 'App\DTO\Profile\ProfileOutput'), 'private');
}
return $this->json(ServiceUtil::processSuccessful());
}
/**
* @Route("/qcm-result", name="qcm_result.save", methods={"POST"})
*/
public function QcmResult(Request $request)
{
$response = json_decode($request->getContent(), 1);
if ($response['token'] && $response['email']) {
$profile = $this->currentRepo->getProfileByToken($response['email'], $response['token']);
if ($profile) {
$dataQcmResults = [
'isDoneTest' => $response['isDoneTest'],
'questions' => $response['questions']
];
$profile->setQcmResults($dataQcmResults);
$this->currentRepo->save($profile);
} else {
return $this->json(ServiceUtil::processFailed([BadRequestException::NO_ENTITY]));
}
} else {
return $this->json(ServiceUtil::processFailed([BadRequestException::WRONG_INPUT]));
}
return $this->json(ServiceUtil::processSuccessful());
}
/**
* @Route("/{_locale}/scolarite", requirements={"_locale": "en|fr"}, defaults={"_locale"="fr"}, name="user.scolarite")
*/
public function scolarite(TranslatorInterface $translator)
{
if (!$this->getUser()) return $this->redirectToRoute('home');
$userId = $this->getUser()->getId();
$profile = $this->profileRepo->getProfileByUserId(['filter_id' => $userId]);
if($profile['status']['id'] != Status::STATUS_STUDENT_ENROLLED) return $this->redirectToRoute('home');
$siteName = $this->getParameter('site_name');
$this->addTitle($translator->trans(
'scolarite.title',
[
'%siteName%' => $siteName
]
));
$this->setDescription($translator->trans(
'scolarite.desc',
[
'%siteName%' => $siteName
]
));
return $this->render('scolarite/index.html.twig', ['profile' => $profile]);
}
/**
* @Route("/{_locale}/inscription", requirements={"_locale": "en|fr"}, defaults={"_locale"="fr"}, name="user.inscription")
*/
public function inscription(TranslatorInterface $translator)
{
if (!$this->getUser()) return $this->redirectToRoute('home');
$userId = $this->getUser()->getId();
$profile = $this->profileRepo->getProfileByUserId(['filter_id' => $userId]);
if($profile['status']['id'] != Status::STATUS_STUDENT_ELIGIBLE) return $this->redirectToRoute('home');
$siteName = $this->getParameter('site_name');
$this->addTitle($translator->trans(
'inscription.title',
[
'%siteName%' => $siteName
]
));
$this->setDescription($translator->trans(
'inscription.desc',
[
'%siteName%' => $siteName
]
));
return $this->render('inscription/index.html.twig', []);
}
/**
* @Route("/profile/upload-file", name="profile.upload_file")
*/
public function uploadFile(Request $request)
{
if (!$this->getUser()) return $this->json(ServiceUtil::processFailed(['message' => "Unauthorized"]));
$userId = $this->getUser()->getId();
$profile = $this->profileRepo->findOneBy(['user' => $userId]);
$result = $this->profileFileService->saveFiles($profile, $request);
$renderedMacro = $this->render('scolarite/wapper.macro.twig.html', ['item' => $result[0]]);
return $this->json(ServiceUtil::processSuccessful([$renderedMacro]));
}
/**
* @Route("/profile/remove-file", name="profile.remove_file")
*/
public function removeFile(Request $request, TranslatorInterface $translator)
{
if (!$this->getUser()) return $this->json(ServiceUtil::processFailed(['message' => "Unauthorized"]));
$profileFile = $this->profileFileService->get($request->request->get('id'));
$this->profileFileService->removeProfileFilesByProfileFilesId($profileFile);
return $this->json(ServiceUtil::processSuccessful());
}
}