<?php
namespace App\Controller;
use Exception;
use App\Entity\Image;
use App\Form\TestType;
use App\Form\ImageType;
use App\Entity\AccountForm;
use App\Entity\ImageProfil;
use App\Entity\ImageGallery;
use App\Form\AccountFormType;
use App\Form\ImageSingleType;
use App\Form\ImageGalleryType;
use PhpParser\Node\Stmt\TryCatch;
use App\Repository\UserRepository;
use App\Form\ImageGalleryItemsType;
use App\Repository\ImageRepository;
use App\Repository\OrdersRepository;
use Symfony\Component\Asset\Package;
use App\Service\Payment\StripeService;
use Doctrine\ORM\PersistentCollection;
use App\Service\Payment\MangopayService;
use App\Service\PushNotificationService;
use App\Repository\AccountFormRepository;
use App\Repository\ImageProfilRepository;
use Symfony\Component\HttpFoundation\Request;
use Stripe\Exception\UnexpectedValueException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\ItemsGalleryVitrineRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Stripe\Exception\SignatureVerificationException;
use Symfony\Component\Serializer\Encoder\JsonDecode;
use App\Repository\SubscriptionPushServiceRepository;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\Entity;
use Stripe\Stripe;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\MakerBundle\Str;
use Symfony\Component\Asset\VersionStrategy\EmptyVersionStrategy;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class AccountFormController extends AbstractController
{
private $stripeApi;
public function __construct(UrlGeneratorInterface $urlGeneratorInterface, EntityManagerInterface $em)
{
$this->stripeApi = new StripeService($urlGeneratorInterface,$em);
}
/**
* @Route("/setMangoPayCredentials", name="register.mangopay")
*/
public function setMangoPayCredentials(AccountFormRepository $accountFormRepository, MangopayService $mangopayService)
{
$accountForms = $accountFormRepository->findAll();
foreach($accountForms as $accountForm ){
if (!$accountForm->getMangopayUserId()){
//$mangoPayUser = $mangopayService->createMangoUserLegal($accountForm);
//$mangopayService->createWallet()
};
}
return new JsonResponse("Modifications effectuées");
}
/**
* @Route("/get-start/{id}", name="register.start" )
*/
public function getStart($id, request $request, AccountFormRepository $accountFormRepository)
{
// ceci est un test git remote
// get the user which are rated the pro from the database
$accountForm = $accountFormRepository->find($id);
$arrStart = $accountForm->getStart();
//$arrUserRating = (empty($arrStart)) ? ['users'] :json_decode($arrStart,true);
$arrUserRating = [];
$arrUserRating['users'] = 0;
$sumStart = 0;
// get the number of starts form the input
$start = $request->request->get('start');
// get the logged user's id
if($this->getUser() !== null){
$userId =$this->getUser()->getId();
// if user already rate the pro
if($arrUserRating !== null){
$userHasRated = array_key_exists($userId, $arrUserRating);
if($userHasRated){
$this->addFlash('notice', 'Votre avis est déjà enregistré');
}
}
if($start !== null && $userId !== null ){
// set the $arrUserRating
/* if(empty($arrUserRating)){
$arrUserRating[''] = array('users');
}*/
$arrUserRating['users'] += ['Id' => $userId, 'startGiven' => $start];
$arrUserRatingDecoded = json_encode($arrUserRating);
$accountForm->setStart($arrUserRatingDecoded);
$em = $this->getDoctrine()->getManager();
$em->persist($accountForm);
$em->flush();
}
}
//$arrStartUpdated = json_decode($arrStartUpdated);
//$arrStartUpdated = ($arrStartUpdated !== null) ? $arrStartUpdated: array();
//dd($arrUserRating['users']['startGiven']);
$nbStart = count($arrUserRating);
if($nbStart > 0){
foreach( $arrUserRating as $userRating ){
$sumStart += $userRating['startGiven'];
}
$averageStart = $sumStart/$nbStart;
$startReviews[] =array('average_start' => round($averageStart), 'nb_start' => $nbStart, 'sumStart' => $sumStart);
}else{
$startReviews[] =array('average_start' => 0, 'nb_start' => 0, 'sumStart' => 0);
}
$startReviews = json_encode($startReviews);
return new Response($startReviews);
}
/**
*
*@Route("/account-register/shop/{id}", name="account.shop.register", methods={"GET", "POST"})
*/
public function AccountShopRegister(Request $request, AccountFormRepository $accountFormRepository, UserRepository $UserRepository, $id, SubscriptionPushServiceRepository $subscriptionPushServiceRepository, PushNotificationService $pushNotificationService, ImageProfilRepository $imageProfilRepository)
{
$this->denyAccessUnlessGranted('ROLE_USER');
$accountForm = $accountFormRepository->find($id);
$userFecht = $this->getUser();
if ( $accountForm )
{
$accountForm->setUser($userFecht);
$userHasAccountUser = true;
$hasStripeAccountConnected = $accountForm->getStripeAccountConnectedId();
$form = $this->createForm(AccountFormType::class, $accountForm);
}
else
{
$userHasAccountUser = false;
$AccountForm = new AccountForm();
$AccountForm->setNom($userFecht->getLastname());
$AccountForm->setPrenom($userFecht->getFirstname());
$AccountForm->setTelephone($userFecht->getPhone());
$form = $this->createForm(AccountFormType::class, $AccountForm);
$hasStripeAccountConnected = null;
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$newAccountForm = $form->getData();
//$identityProof = $form->get('identityProof')->getData();
$EntityManager = $this->getDoctrine()->getManager();
if( !$userHasAccountUser ){
$userFecht->setAccountForm($newAccountForm);
$newAccountForm->setUser($userFecht);
}
try{
$email = $userFecht->getEmail();
$newAccountForm->setMail($email);
$EntityManager->persist($userFecht);
$EntityManager->persist($newAccountForm);
$EntityManager->flush();
if($hasStripeAccountConnected === null){
$this->stripeApi->createStripeAccountConnected($newAccountForm);
}
// $image = $imageProfilRepository->findBy(['user' => $newAccountForm->getUser()->getId()]);
//$imageUrl = ($image != null ) ? "https://coasttocorner.com/images/profils/{$AccountForm->getUser()->getEmail()}/{$image[0]->getUrlImage()}" : '';
//$payload = ['title'=> "Nouveau Restaurant : {$newAccountForm->getMarque()} ",'body' => " Localisation : {$newAccountForm->getVille()} {$newAccountForm->getCodePostal()} \n{$newAccountForm->getDescription()} ", 'url' => "https://coasttocorner.com/category/{$newAccountForm->getCategory()}/store{$newAccountForm->getId()}", 'image' => $imageUrl];
//$pushNotificationService->pushNotification($subscriptionPushServiceRepository, $payload);
return $this->redirectToRoute('profil.user');
} catch(Exception $e){
echo $e->getMessage();
$this->addFlash('error', 'Une erreur est survenue lors de la création de votre compte professionnel : '.$e->getMessage().'. Veuillez réessayer.');
}
} else{
//var_dump($form);
//die();
}
return $this->render('account.html.twig', [
'form' => $form->createView(),
]);
}
/**
*
* @Route("/update/account-connected",name="updateAccountConnected",methods={"GET","POST"})
*/
public function updateAccountConnected(AccountFormRepository $accountFormRepository, StripeService $stripeApi){
$user = $this->getUser();
$accountForm = $accountFormRepository->findOneBy(['user'=> $user->getId()]);
$accountConnectedId = $stripeApi->createStripeAccountConnected($accountForm);
$accountForm->setStripeAccountConnectedId($accountConnectedId);
return new JsonResponse("Modifications effectuées");
}
/**
*
* @Route("/update/account-connected",name="updateAccountConnected",methods={"GET","POST"})
*/
public function verificationSession(AccountFormRepository $accountFormRepository, StripeService $stripeApi){
$user = $this->getUser();
$accountForm = $accountFormRepository->findOneBy(['user'=> $user->getId()]);
$accountConnected = $accountForm->getStripeAccountConnectedId();
$session = $stripeApi->verificationSession($accountConnected);
return $this->redirect($session->url);
}
/**
* @Route("/update/verification-session/{accountConnected}",name="updateVerificationSession",methods={"GET","POST"})
*/
public function updateVerificationSession(AccountFormRepository $accountFormRepository, StripeService $stripeApi, $accountConnected){
$account = $stripeApi->updateVerificationSession($accountConnected);
return new JsonResponse("Modifications effectuées");
}
/**
*
* @Route("/create-kyc/", name="kyc", methods={"GET","POST"})
*/
public function createKyc(AccountFormRepository $accountFormRepository, MangopayService $mangopayService){
$this->denyAccessUnlessGranted('ROLE_USER');
$user = $this->getUser();
$accountForm = $accountFormRepository->findBy(array('user' => $user->getId()));
if (!$accountForm){
return new Response('Veuillez créer un compte professionel avant de compléter votre dossier professionnel en vous rendant sur <a href='.$this->generateUrl("account.shop.register", array('id'=>$user->getId())).'> créer mon compte restaurant/épicerie</a>.');
}
$mangoPayUserId = $accountForm[0]->getMangopayUserId();
$kyc = $mangopayService->createKyc($mangoPayUserId);
return new Response("<p>Votre kyc a été créé avec succès.</p>");
}
/**
*
* @Route("/create-page-kyc/", name="page-kyc", methods={"GET","POST"})
*/
public function CreateKycPageFromFile(AccountFormRepository $accountFormRepository, MangopayService $mangopayService){
$this->denyAccessUnlessGranted('ROLE_USER');
$user = $this->getUser();
$accountForm = $accountFormRepository->findBy(array('user' => $user->getId()));
if (!$accountForm){
return new Response('Veuillez créer un compte professionel avant de compléter votre dossier professionnel en vous rendant sur <a href='.$this->generateUrl("account.shop.register", array('id'=>$user->getId())).'> créer mon compte restaurant/épicerie</a>.');
}
$mangoPayUserId = $accountForm[0]->getMangopayUserId();
$kyc = $mangopayService->createKyc($mangoPayUserId);
$mangopayService->CreateKycPageFromFile($mangoPayUserId, $kyc, '' );
return new Response("<p>Votre kyc a été créé avec succès.</p>");
}
/**
*
*@Route("/account-register/shop/image-gallery/{id}", name="account.shop.image.gallery.register", methods={"GET", "POST"})
*/
public function AccountShopImageGalleryRegister(Request $request, UserRepository $UserRepository, ImageRepository $ImageRepository,ImageRepository $imageRepository,ItemsGalleryVitrineRepository $ItemsGalleryVitrineRepository, $id)
{
// creates a task and gives it some dummy data for this example
$userFecht = $UserRepository->find($id);
$userId = $userFecht->getId();
$AccountForm = $userFecht->getAccountForm();
// Display mains images
// $ImageFecht = $ImageRepository->findOneBy( ["accountForm" => $AccountForm->getId()], ["position" => 1]) ;
$ImageFecht_1 = $ImageRepository->findImageByPosition($AccountForm->getId(), 1 );
$ImageFecht_2 = $ImageRepository->findImageByPosition($AccountForm->getId(), 2 );
$ImageFecht_3 = $ImageRepository->findImageByPosition($AccountForm->getId(), 3 );
$ImageFecht_4 = $ImageRepository->findImageByPosition($AccountForm->getId(), 4 );
$ImageFecht_5 = $ImageRepository->findImageByPosition($AccountForm->getId(), 5 );
$ListImage = array($ImageFecht_1, $ImageFecht_2, $ImageFecht_3, $ImageFecht_4, $ImageFecht_5);
$EntityManager = $this->getDoctrine()->getManager();
//$ImagePosition = $ImageRepository->findBy( ["accountForm" => $id]);
//dump($ImageFecht);
if($ImageFecht_1 != null)
{
$Image1 = $ImageFecht_1;
}
else{
$Image1 = new Image();
}
$Image2 = new Image();
$Image3 = new Image();
$Image4 = new Image();
$Image5 = new Image();
$Image1->setAccountForm($AccountForm);
$Image1->setPosition(1);
$Image2->setAccountForm($AccountForm);
$Image2->setPosition(2);
$Image3->setAccountForm($AccountForm);
$Image3->setPosition(3);
$Image4->setAccountForm($AccountForm);
$Image4->setPosition(4);
$Image5->setAccountForm($AccountForm);
$Image5->setPosition(5);
if( $AccountForm->getImage() !== null )
{
$Image = $AccountForm->getImage();
}
if ( $AccountForm !== null && !$AccountForm->getImage() )
{
//$formImage1 = $this->createForm(ImageType::class, $Image1);
$formImage2 = $this->get('form.factory')->createNamed('image2', ImageType::class, $Image2 );
$formImage3 = $this->get('form.factory')->createNamed('image3', ImageType::class, $Image3 );
$formImage4 = $this->get('form.factory')->createNamed('image4', ImageType::class, $Image4 );
$formImage5 = $this->get('form.factory')->createNamed('image5', ImageType::class, $Image5 );
//$imageCollection = array($formImage1, $formImage2, $formImage3, $formImage4,$formImage5);
}
if(!empty($ListImage) && $AccountForm !== null )
{
if( $AccountForm !== null && $ImageFecht_1 )
{
$formImage1 = $this->get('form.factory')->createNamed('image1', ImageType::class, $ImageFecht_1 );
}
else
{
$formImage1 = $this->get('form.factory')->createNamed('image1', ImageType::class, $Image1 );
}
if( $AccountForm !== null && $ImageFecht_2 )
{
$formImage2 = $this->get('form.factory')->createNamed('image2', ImageType::class, $ImageFecht_2 );
}
else
{
$formImage2 = $this->get('form.factory')->createNamed('image2', ImageType::class, $Image2 );
}
if( $AccountForm !== null && $ImageFecht_3 )
{
$formImage3 = $this->get('form.factory')->createNamed('image3', ImageType::class, $ImageFecht_3 );
}
else
{
$formImage3 = $this->get('form.factory')->createNamed('image3', ImageType::class, $Image3 );
}
if( $AccountForm !== null && $ImageFecht_4 )
{
$formImage4 = $this->get('form.factory')->createNamed('image4', ImageType::class, $ImageFecht_4 );
}
else
{
$formImage4 = $this->get('form.factory')->createNamed('image4', ImageType::class, $Image4 );
}
if( $AccountForm !== null && $ImageFecht_5 )
{
$formImage5 = $this->get('form.factory')->createNamed('image5', ImageType::class, $ImageFecht_5 );
}
else
{
$formImage5 = $this->get('form.factory')->createNamed('image5', ImageType::class, $Image5 );
}
}
else
{
return $this->redirectToRoute('profil.user');
}
$formImage1->handleRequest($request);
$formImage2->handleRequest($request);
$formImage3->handleRequest($request);
$formImage4->handleRequest($request);
$formImage5->handleRequest($request);
if ($formImage1->isSubmitted() && $formImage1->isValid())
{
$ImageGallery = $formImage1->getData();
$ImageGallery->setAccountForm($AccountForm);
$EntityManager->persist($ImageGallery);
$EntityManager->persist($AccountForm);
$EntityManager->flush();
if(!is_dir(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}"))
{
if(!is_dir(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}")){
mkdir( dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}", 0777, true);
}
mkdir( dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}", 0777, true);
}
/* Create the directory principale for the princiaple image */
if(!is_dir(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/primary_image"))
{
// dd($AccountForm->getMail());
mkdir( dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/primary_image", 0777, true);
}
if(!file_exists(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}"))
{
@rename(dirname(__DIR__, 2)."/public_html/images/categories/{$ImageGallery->getUrlImage()}", dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}");
$path_file_image = dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}";
// redimension image
/*if(file_exists($path_file_image) )
{
if(pathinfo($path_file_image, PATHINFO_EXTENSION) === ('jpg' || 'jpeg' || 'JPG' || 'JPEG'))
{
$filename = imagecreatefromjpeg($path_file_image);
}
else
{
$filename = imagecreatefrompng($path_file_image);
}
$max_resolution = 600;
//resolution
$original_width = imagesx($filename);
$original_height = imagesy($filename);
//ratio
//try width first
$ratio = $max_resolution / $original_width;
$new_width = $max_resolution;
$new_height = $original_height * $ratio;
//if height failed
if($new_height > $max_resolution)
{
$ratio = $max_resolution / $original_height;
$new_height = $max_resolution;
$new_width = $original_width * $ratio;
}
$new_img = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($new_img, $filename,0,0,0,0,$new_width,$new_height, $original_width, $original_height);
if(pathinfo($path_file_image, ['PATHINFO_EXTENSION']) === ('jpg' || 'jpeg' || 'JPG' || 'JPEG'))
{
imagejpeg($new_img,$path_file_image);
}
else
{
imagepng($new_img,$path_file_image);
}
}*/
}
}
if( $formImage2->isSubmitted() && $formImage2->isValid() )
{
$ImageGallery = $formImage2->getData();
$EntityManager->persist($ImageGallery);
$EntityManager->flush();
}
if ($formImage2->isSubmitted() && $formImage2->isValid())
{
$ImageGallery = $formImage2->getData();
$ImageGallery->setAccountForm($AccountForm);
$EntityManager->persist($ImageGallery);
$EntityManager->persist($AccountForm);
$EntityManager->flush();
if(!is_dir(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}"))
{
mkdir( dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}");
}
/* Create the directory principale for the princiaple image */
if(!is_dir(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/primary_image"))
{
mkdir( dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/primary_image");
}
if(!file_exists(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}"))
{
@rename(dirname(__DIR__, 2)."/public_html/images/categories/{$ImageGallery->getUrlImage()}", dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}");
$path_file_image = dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}";
// redimension image
/* if(file_exists($path_file_image))
{
$filename = imagecreatefromjpeg($path_file_image);
$max_resolution = 900;
//resolution
$original_width = imagesx($filename);
$original_height = imagesy($filename);
//ratio
//try width first
$ratio = $max_resolution / $original_width;
$new_width = $max_resolution;
$new_height = $original_height * $ratio;
//if height failed
if($new_height > $max_resolution)
{
$ratio = $max_resolution / $original_height;
$new_height = $max_resolution;
$new_width = $original_width * $ratio;
}
$new_img = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($new_img, $filename,0,0,0,0,$new_width,$new_height, $original_width, $original_height);
imagejpeg($new_img,$path_file_image);
*/
/*
$cropperResult = $_POST["cropperResult"];
dump($cropperResult);
$cropperResult = json_decode($cropperResult);
$im = imagecreatefromjpeg($path_file_image);
$size = min(imagesx($im), imagesy($im));
$im2 = imagecrop($im, [ 'x' => $cropperResult->x, 'y' => $cropperResult->y, 'width' => $cropperResult->width, 'height' => $cropperResult->height ]);
if ($im2 !== FALSE) {
imagejpeg($im2, $path_file_image);
}
}*/
}
}
if ($formImage3->isSubmitted() && $formImage3->isValid())
{
$ImageGallery = $formImage3->getData();
$ImageGallery->setAccountForm($AccountForm);
$EntityManager->persist($ImageGallery);
$EntityManager->persist($AccountForm);
$EntityManager->flush();
if(!is_dir(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}"))
{
mkdir( dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}");
}
/* Create the directory principale for the princiaple image */
if(!is_dir(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/primary_image"))
{
mkdir( dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/primary_image");
}
if(!file_exists(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}"))
{
@rename(dirname(__DIR__, 2)."/public_html/images/categories/{$ImageGallery->getUrlImage()}", dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}");
$path_file_image = dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}";
// redimension image
/*if(file_exists($path_file_image))
{
$filename = imagecreatefromjpeg($path_file_image);
$max_resolution = 600;
//resolution
$original_width = imagesx($filename);
$original_height = imagesy($filename);
//ratio
//try width first
$ratio = $max_resolution / $original_width;
$new_width = $max_resolution;
$new_height = $original_height * $ratio;
//if height failed
if($new_height > $max_resolution)
{
$ratio = $max_resolution / $original_height;
$new_height = $max_resolution;
$new_width = $original_width * $ratio;
}
$new_img = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($new_img, $filename,0,0,0,0,$new_width,$new_height, $original_width, $original_height);
imagejpeg($new_img,$path_file_image);
}*/
}
}
if ($formImage4->isSubmitted() && $formImage4->isValid())
{
$ImageGallery = $formImage4->getData();
$ImageGallery->setAccountForm($AccountForm);
$EntityManager->persist($ImageGallery);
$EntityManager->persist($AccountForm);
$EntityManager->flush();
if(!is_dir(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}"))
{
mkdir( dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}");
}
/* Create the directory principale for the princiaple image */
if(!is_dir(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/primary_image"))
{
mkdir( dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/primary_image");
}
if(!file_exists(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}"))
{
@rename(dirname(__DIR__, 2)."/public_html/images/categories/{$ImageGallery->getUrlImage()}", dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}");
$path_file_image = dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}";
// redimension image
if(file_exists($path_file_image))
{
$filename = imagecreatefromjpeg($path_file_image);
$max_resolution = 600;
//resolution
$original_width = imagesx($filename);
$original_height = imagesy($filename);
//ratio
//try width first
$ratio = $max_resolution / $original_width;
$new_width = $max_resolution;
$new_height = $original_height * $ratio;
//if height failed
if($new_height > $max_resolution)
{
$ratio = $max_resolution / $original_height;
$new_height = $max_resolution;
$new_width = $original_width * $ratio;
}
$new_img = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($new_img, $filename,0,0,0,0,$new_width,$new_height, $original_width, $original_height);
imagejpeg($new_img,$path_file_image);
}
}
}
if ($formImage5->isSubmitted() && $formImage5->isValid())
{
$ImageGallery = $formImage5->getData();
$ImageGallery->setAccountForm($AccountForm);
$EntityManager->persist($ImageGallery);
$EntityManager->persist($AccountForm);
$EntityManager->flush();
if(!is_dir(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}"))
{
mkdir( dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}");
}
/* Create the directory principale for the princiaple image */
if(!is_dir(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/primary_image"))
{
mkdir( dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/primary_image");
}
if(!file_exists(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}"))
{
@rename(dirname(__DIR__, 2)."/public_html/images/categories/{$ImageGallery->getUrlImage()}", dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}");
$path_file_image = dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$ImageGallery->getUrlImage()}";
// redimension image
/*if(file_exists($path_file_image))
{
$filename = imagecreatefromjpeg($path_file_image);
$max_resolution = 600;
//resolution
$original_width = imagesx($filename);
$original_height = imagesy($filename);
//ratio
//try width first
$ratio = $max_resolution / $original_width;
$new_width = $max_resolution;
$new_height = $original_height * $ratio;
//if height failed
if($new_height > $max_resolution)
{
$ratio = $max_resolution / $original_height;
$new_height = $max_resolution;
$new_width = $original_width * $ratio;
}
$new_img = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($new_img, $filename,0,0,0,0,$new_width,$new_height, $original_width, $original_height);
imagejpeg($new_img,$path_file_image);
}*/
}
}
/* Manager Images Gallery */
$imagesGalleryFetch = $ItemsGalleryVitrineRepository->findBy(['accountForm' => $AccountForm->getId()]);
$formImageGallery = $this->createForm(ImageGalleryItemsType::class);
$formImageGallery->handleRequest($request);
if($formImageGallery->isSubmitted() && $formImageGallery->isValid())
{
$imagesGallery = $formImageGallery->getData();
foreach ($imagesGallery as $containerImagesGallery)
{
foreach($containerImagesGallery as $images)
{
$images = $images->setAccountForm($AccountForm);
$EntityManager->persist($images);
try{
$EntityManager->flush();
} catch(UniqueConstraintViolationException $e)
{
$this->addFlash('warning', 'Vous avez déjà enregistré cette image');
}
if(!file_exists(dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$images->getUrlImage()}"))
{
rename(dirname(__DIR__, 2)."/public_html/images/categories/{$images->getUrlImage()}", dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$images->getUrlImage()}");
$path_file_image = dirname(__DIR__, 2)."/public_html/images1/categories/{$AccountForm->getCategory()}/store_{$AccountForm->getMail()}/{$images->getUrlImage()}";
}
}
}
}
return $this->render('account.image-gallery.html.twig', [
'imagesGalleryFetch' => $imagesGalleryFetch,
'formImagesGallery' => $formImageGallery->createView(),
'FormImage1' => $formImage1->createView(),
'FormImage2' => $formImage2->createView(),
'FormImage3' => $formImage3->createView(),
'FormImage4' => $formImage4->createView(),
'FormImage5' => $formImage5->createView(),
]);
}
/**
* @Route("account-register/products-manager", name="products-manager")
*/
public function productsManager(ItemsGalleryVitrineRepository $itemsGalleryVitrineRepository, Request $request,ValidatorInterface $validator )
{
$this->denyAccessUnlessGranted('ROLE_BUSINESS');
$user = $this->getUser();
$accountForm = $user->getAccountForm();
$EntityManager = $this->getDoctrine()->getManager();
$imagesGalleryFetch = $itemsGalleryVitrineRepository->findBy(['accountForm' => $accountForm->getId()]);
$formImageGallery = $this->createForm(ImageGalleryItemsType::class);
$formImageGallery->handleRequest($request);
if($formImageGallery->isSubmitted() && $formImageGallery->isValid())
{
$imagesGallery = $formImageGallery->getData();
/* var_dump($imagesGallery);
die();*/
foreach ($imagesGallery as $containerImagesGallery)
{
foreach($containerImagesGallery as $images)
{
$images = $images->setAccountForm($accountForm);
$images->setUpdatedAt(new \DateTime('now'));
$errors = $validator->validate($images);
if (count($errors) > 0) {
foreach ($errors as $error) {
echo $error->getMessage() . "<br>";
}
}
// dd($images);
$EntityManager->persist($images);
try{
$EntityManager->flush();
} catch(UniqueConstraintViolationException $e)
{
$this->addFlash('warning', 'Vous avez déjà enregistré cette image');
}
if(!file_exists(dirname(__DIR__, 2)."/public_html/images1/categories/{$accountForm->getCategory()}/store_{$accountForm->getMail()}/{$images->getUrlImage()}"))
{
@rename(dirname(__DIR__, 2)."/public_html/images/categories/{$images->getUrlImage()}", dirname(__DIR__, 2)."/public_html/images1/categories/{$accountForm->getCategory()}/store_{$accountForm->getMail()}/{$images->getUrlImage()}");
$path_file_image = dirname(__DIR__, 2)."/public_html/images1/categories/{$accountForm->getCategory()}/store_{$accountForm->getMail()}/{$images->getUrlImage()}";
}
}
}
}
return $this->render('products.manager.html.twig',[
'formImagesGallery' => $formImageGallery->createView(),
'imagesGalleryFetch' => $imagesGalleryFetch
]);
}
/**
* @Route("account-register/shop/delete-image/{id}", name="delete.image", methods={ "GET", "POST" } )
*
*/
public function deleteImage($id, Request $request, UserRepository $UserRepository, ImageRepository $ImageRepository, AccountFormRepository $AccountFormRepository)
{
$this->denyAccessUnlessGranted('ROLE_USER');
$Image = $ImageRepository->find($id);
if($Image !== null)
{
$EntityManager = $this->getDoctrine()->getManager();
$AccountForm = $Image->getAccountForm();
if($AccountForm !== null)
{
$AccountFormHasDeleted = $AccountFormRepository->find($AccountForm->getId());
$AccountFormHasDeleted = $AccountFormHasDeleted->setUser(null);
$EntityManager->persist($AccountFormHasDeleted);
$EntityManager->flush();
$EntityManager->remove($Image);
}
}
return $this->redirectToRoute('account.shop.image.gallery.register', ['id' => $UserRepository->find($this->getUser()->getId())->getId()]);
}
/**
*@Route("delete-account/{id}", name="delete.account", methods={ "GET", "POST" } )
*
*/
public function deleteAccount($id, Request $request, UserRepository $UserRepository, Session $session, AccountFormRepository $AccountFormRepository, AccountForm $AccountForm, StripeService $stripeService)
{
$this->denyAccessUnlessGranted('ROLE_USER');
$User = $UserRepository->find($id);
$AccountForm = $User->getAccountform();
if($AccountForm && $AccountForm !== NULL )
{
$customerStripeId = $stripeService->listSubscriptions($User->getCustomerStripeId());
if($customerStripeId)
{
$stripeService->cancelSubscription($customerStripeId,$User);
$this->addFlash('success', 'Votre abonnement a bien été annulé.');
}
}
$EntityManager = $this->getDoctrine()->getManager();
// deleted $AccountForm related at $User
if($AccountForm !== null)
{
$AccountFormHasDeleted = $User->getAccountform();
$UserWithAccountFormNull = $User->setAccountform(null);
//$AccountFormHasDeleted = $AccountFormRepository->find($AccountFormHasDeleted->getId());
$AccountFormHasDeleted= $AccountFormHasDeleted->setUser(null);
if(!empty($AccountFormHasDeleted->getImage()))
{
$images = $AccountFormHasDeleted->getImage();
foreach($images as $img)
{
$AccountFormHasDeleted->removeImage($img);
}
}
if($AccountFormHasDeleted->getOpeningHours())
{
$OpeningHours = $AccountFormHasDeleted->getOpeningHours()->setAccountForm(null);
$AccountFormHasDeleted = $AccountFormHasDeleted->setOpeningHours(null);
$EntityManager->persist($OpeningHours);
}
$EntityManager->persist($AccountFormHasDeleted);
$EntityManager->flush();
$EntityManager->remove($AccountFormHasDeleted);
}
$EntityManager->flush();
$this->get('security.token_storage')->setToken(null);
$session->invalidate();
$this->switchAccount($request);
return $this->render('delete.account.html.twig');
}
/**
* @Route("get-items-gallery-vitrine/{idAccountForm}", name="items.vitrine")
*/
public function getItemsVitrine(ItemsGalleryVitrineRepository $itemsGalleryVitrineRepository, $idAccountForm)
{
$itemsGalleryVitrine = $itemsGalleryVitrineRepository->findBy(['accountForm'=> $idAccountForm]);
return $this->render('items.gallery.vitrine.html.twig', ['itemsGalleryVitrine' => $itemsGalleryVitrine]);
}
/**
*@Route("delete-shop/{id}", name="delete.shop", methods={ "GET", "POST" } )
*
*/
public function deleteShop($id, Request $request, UserRepository $UserRepository, AccountFormRepository $AccountFormRepository, StripeService $stripeService)
{
$this->denyAccessUnlessGranted('ROLE_USER');
$User = $UserRepository->find($id);
$AccountForm = $User->getAccountform();
if($AccountForm !== NULL )
{
$subscriptionIds = $stripeService->listSubscriptions($User->getCustomerStripeId());
//dd($subscriptionId);
if(!$subscriptionIds->isEmpty())
{
foreach($subscriptionIds as $subscriptionId){
$stripeService->cancelSubscription($subscriptionId->id,$User);
}
$this->addFlash('success', 'Votre abonnement a bien été annulé.');
}
$AccountFormHasDeleted = $AccountFormRepository->find($AccountForm->getId());
//dd($AccountFormHasDeleted);
$AccountFormHasDeleted = $AccountFormHasDeleted->setUser(null);
$EntityManager = $this->getDoctrine()->getManager();
$images = $AccountFormHasDeleted->getImage();
foreach($images as $image)
{
$EntityManager->remove($image);
}
$userAccount = $User->setAccountform(null);
$EntityManager->persist($userAccount);
$EntityManager->remove($AccountFormHasDeleted);
$EntityManager->flush();
$this->addFlash('success', 'Votre boutique a bien été cloturée.');
$this->switchAccount($request);
//return $this->render('successDeleteShop.html.twig');
}
return $this->render('successDeleteShop.html.twig');
}
/**
* @Route("/account-register/shop/dashboard-stripe/{connectedAccountId}", name="account.shop.dashboard.stripe", methods={"GET", "POST"})
*/
public function dashboardStripe($connectedAccountId, StripeService $stripeService, urlGeneratorInterface $urlGeneratorInterface){
try {
// Replace `$connectedAccountId` with the actual ID of the connected account
$loginLink = $this->stripeApi->getLoginLink($connectedAccountId);
// Redirect the user to the dashboard login link
header('Location: ' . $loginLink->url);
exit();
} catch (\Stripe\Exception\ApiErrorException $e) {
// Log and handle errors
error_log('Stripe API Error: ' . $e->getMessage());
exit('An error occurred while generating the dashboard login link.');
}
}
/**
* @Route("/account-register/subscription", name="account.shop.subscription", methods={"GET", "POST"})
*/
public function createSubscription(StripeService $stripeService){
$user = $this->getUser();
if (!$user) {
$this->addFlash('error', 'Vous devez être connecté pour accéder à cette page');
return $this->redirectToRoute('profil.user');
}
$customerEmail = $user->getEmail();
$subscription = $stripeService->createCheckoutSessionSubscription($user);
return $this->redirect($subscription->url);
}
/**
* @Route("/account-register/ads-first", name="account.shop.ads.first", methods={"GET", "POST"})
*/
public function createAdsFirst(StripeService $stripeService){
$user = $this->getUser();
if (!$user) {
$this->addFlash('error', 'Vous devez être connecté pour accéder à cette page');
return $this->redirectToRoute('profil.user');
}
$customerEmail = $user->getEmail();
// $subscription = $stripeService->createCheckoutSessionAds($user);
$subscriptionId = $user->getAccountForm()->getSubscription();
$subscription = $stripeService->updateSubscription($user, $subscriptionId);
//return $this->redirect($subscription->url);
return $this->redirectToRoute('profil.user');
}
/**
* @Route("/account-register/plan", name="account.shop.plan", methods={"GET", "POST"})
*/
public function viewPlan(){
$user = $this->getUser();
$logged = true;
if (!$user) {
$this->addFlash('error', 'Vous devez être connecté pour pouvoir souscrire à l\'offre Premium');
$logged = false;
}
return $this->render('view.plan.html.twig', ['logged' => $logged]);
}
/**
* @Route("/event-account-connected/{typeAccount}", name="account.shop.event.account.connected", methods={"GET", "POST"})
*/
public function eventAccountConnected($typeAccount, AccountFormRepository $accountFormRepository, Request $request, EntityManagerInterface $entityManager){
$this->stripeApi->stripeWebhookHandler($typeAccount, $accountFormRepository, $request, $entityManager);
return new Response('Webhook received');
}
/**
* @Route("switch-account", name="switch.account")
*/
public function switchAccount(Request $request){
$session = $request->getSession();
$profil = $session->get('profil');
if($profil ==='jobber'){
$session->set('profil','customer');
}
else{
$session->set('profil','jobber');
}
$profil = $request->getSession()->get('profil');
return new JsonResponse(['profil'=>$profil]);
}
/**
* @Route("profil-account-session", name="profil.account.session")
*/
public function profilAccount(Request $request){
$profil = $request->getSession()->get('profil');
return new JsonResponse(['profil'=>$profil]);
}
/**
* @Route("dashboard-stripe-customer", name="dashboard.stripe.customer")
*/
public function dashboardStripeCustomer(StripeService $stripeService){
$user = $this->getUser();
$loginLink = $stripeService->getBillingPortalCustomer($user);
return $this->redirect($loginLink->url);
}
/**
* @Route("payment-success-ads", name="payment.success.ads", methods={"GET", "POST"})
*/
public function paymentSuccess(Request $request, StripeService $stripeService){
$user = $this->getUser();
return $this->render('payment_success_ads.html.twig', ['user' => $user]);
}
}