<?php
namespace App\Manager\Purchase;
use App\Entity\Management\Subscription\PaymentFutur;
use App\Entity\Educational\Course;
use App\Entity\Educational\Serie;
use App\Entity\Management\Subscription\Discount;
use App\Entity\Management\Subscription\Formule;
use App\Entity\Management\Subscription\Offer;
use App\Entity\Management\Subscription\Options;
use App\Entity\Management\Subscription\OptionsSubscription;
use App\Entity\Management\Subscription\RegisterInfosTunnel;
use App\Entity\Management\Subscription\Subscription;
use App\Entity\Management\Subscription\SubscriptionOptions;
use App\Entity\Users\Child;
use App\Entity\Users\Parents;
use App\Entity\Users\StudentsParents;
use App\Entity\Educational\Speciality;
use App\Entity\Educational\Discipline;
use App\Entity\Users\User;
use App\Service\Mailer\SubscriptionMailer;
use App\Service\StripeService;
use Doctrine\ORM\EntityManagerInterface;
use http\Client\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class PurchaseTunnelManager
{
private EntityManagerInterface $em;
private RequestStack $requestStack;
private $request;
private $passwordHasher;
private StripeService $stripeService;
private SubscriptionMailer $mailer;
public function __construct(
EntityManagerInterface $em,
RequestStack $requestStack,
UserPasswordHasherInterface $passwordHasher,
StripeService $stripeService,
SubscriptionMailer $mailer
)
{
$this->em = $em;
$this->requestStack = $requestStack;
$this->request = $this->requestStack->getCurrentRequest();
$this->passwordHasher = $passwordHasher;
$this->stripeService = $stripeService;
$this->mailer = $mailer;
}
public function summary($infos,Offer $offer)
{
$tab = [];
$i = 1;
foreach ($infos['parents_registration']['childrenForm'] as $child){
$tab[] = [
'firstname' => $child['firstname'],
'unitprice' => $offer->getPrice(),
'remise' => $i==1?0:((1<$i && $i<4)?$i*10:30)
];
$tab[$i-1]['price'] = round($tab[$i-1]['unitprice'] - $tab[$i-1]['unitprice'] * $tab[$i-1]['remise']/100,2);
$i++;
}
return $tab;
}
public function summaryEndEssaiGratuit($childrenIDS,Offer $offer)
{
$tab = [];
$i = 1;
foreach ($childrenIDS as $childID){
$child = $this->em->getRepository(Child::class)->find($childID);
$tab[] = [
'firstname' => $child->getFirstname(),
'unitprice' => $offer->getPrice(),
'remise' => $i==1?0:((1<$i && $i<4)?$i*10:30)
];
$tab[$i-1]['price'] = round($tab[$i-1]['unitprice'] - $tab[$i-1]['unitprice'] * $tab[$i-1]['remise']/100,2);
$i++;
}
return $tab;
}
public function totalPrice($nbr,$price){
$som = 0;
for($i=1;$i<=$nbr;$i++){
if(1<$i){
$som= $som + ($price - ($price * (($i*10)/100)));
}else{
$som+=$price;
}
}
return $som;
}
public function registrationParent($infos = [])
{
if(!empty($infos)){
$customInfos = $infos;
}else{
$session = $this->requestStack->getSession();
$customInfos = $session->get('customInfosSecondStep')["parents_registration_second_step"];
}
$parents = new Parents();
$parents->setFirstname($customInfos["firstname"]);
$parents->setLastname($customInfos["lastname"]);
$parents->setUsername($customInfos["email"]["first"]);
$parents->setEmail($customInfos["email"]["first"]);
// $parents->setPhone($customInfos["phone"]);
$parents->setPassword($this->passwordHasher->hashPassword($parents,$customInfos["plainPassword"]));
$parents->setRoles(['ROLE_USER', 'ROLE_PARENTS']);
$parents->setPopinShareGoodDeal(true);
$parents->setIsCgu(true);
$parents->setOrigin(0);
$parents->setParentEmail($customInfos["email"]["first"]);
$parents->setLegalGuardianAuthorization(true);
$parents->setEmailValidationToken(0);
$parents->setEmailValidationTokenRequestedAt(new \DateTime('now'));
$parents->setStatus(200);
$parents->setEnabled(1);
return $parents;
}
public function createParentTunnel($customInfosSecondStep){
$parents = new Parents();
if( is_array($customInfosSecondStep["email"]) && array_key_exists("first",$customInfosSecondStep["email"])){
$email = $customInfosSecondStep["email"]["first"];
}else{
$email = $customInfosSecondStep["email"];
}
if(is_array($customInfosSecondStep["plainPassword"]) && array_key_exists("first",$customInfosSecondStep['plainPassword'])){
$password = $customInfosSecondStep['plainPassword']['first'];
}else{
$password = $customInfosSecondStep['plainPassword'];
}
$parents->setFirstname($customInfosSecondStep["firstname"]);
$parents->setLastname($customInfosSecondStep["lastname"]);
$parents->setUsername($email);
$parents->setEmail($email);
$parents->setCity($customInfosSecondStep["city"]);
$parents->setPostalCode($customInfosSecondStep["postalCode"]);
// $parents->setRegistrationProfile($customInfosSecondStep["registrationProfile"]);
if (array_key_exists("isNewsletter",$customInfosSecondStep) && $customInfosSecondStep["isNewsletter"] == true){
$isNewsletter = true;
}else{
$isNewsletter = false;
}
if (array_key_exists("phone",$customInfosSecondStep)){
$parents->setPhone($customInfosSecondStep['phone']);
}
$parents->setIsNewsletter($isNewsletter);
$parents->setPassword($this->passwordHasher->hashPassword($parents,$password));
$parents->setRoles(['ROLE_USER', 'ROLE_PARENTS']);
$parents->setPopinShareGoodDeal(true);
$parents->setIsCgu(true);
$parents->setOrigin(0);
$parents->setParentEmail($email);
$parents->setLegalGuardianAuthorization(true);
$parents->setEmailValidationToken(0);
$parents->setEmailValidationTokenRequestedAt(new \DateTime('now'));
$parents->setStatus(200);
$parents->setEnabled(1);
$parents->setIsVerified(true);
return $parents;
}
public function registrationParentEssaiGratuit()
{
$session = $this->requestStack->getSession();
$customInfosSecondStep = $session->get('customInfosSecondStep')["parents_registration_second_step"];
return $this->createParentTunnel($customInfosSecondStep);
}
public function registrationStudent($data)
{
if(!empty($data)){
$child = new Child();
$child->setFirstname($data['firstname']);
$course = $this->em->getRepository(Course::class)->find($data['course']);
$serie = $this->em->getRepository(Serie::class)->findOneBySlug('generale');
$child->setCourse($course);
$child->setSerie($serie);
//?offre=bac-francais
if(array_key_exists('phone',$data)){
$child->setPhone($data['phone']);
}
if(array_key_exists('email',$data)){
$child->setParentEmail($data["email"]);
}
$child->setEmail(uniqid()."@lbp.com");
$child->setUsername($child->getEmail());
$child->setRoles(['ROLE_STUDENT']);
// $child->setGender($data['gender']);
$child->setPassword($this->passwordHasher->hashPassword($child,uniqid()));
$child->setEmailValidationToken(0);
$child->setEmailValidationTokenRequestedAt(new \DateTime('now'));
$child->setIsVerified(true);
return $child;
}
return null;
}
public function registrationStudentEssaiGratuit($data)
{
if(!empty($data)){
$child = new Child();
$child->setFirstname($data['firstname']);
$course = $this->em->getRepository(Course::class)->find($data['course']);
$serie = $this->em->getRepository(Serie::class)->findOneBySlug('generale');
$child->setCourse($course);
$child->setSerie($serie);
$child->setEmail(uniqid()."@lbp.com");
$child->setUsername($child->getEmail());
$child->setRoles(['ROLE_STUDENT']);
$child->setIsVerified(true);
// $child->setGender($data['gender']);
$child->setPassword($this->passwordHasher->hashPassword($child,uniqid()));
$child->setEmailValidationToken(0);
$child->setEmailValidationTokenRequestedAt(new \DateTime('now'));
return $child;
}
return null;
}
public function registrationStudentProfilEleveEssaiGratuit($data)
{
$session = $this->requestStack->getSession();
$customInfosSecondStep = $session->get('customInfosSecondStep')["parents_registration_second_step"];
if(!empty($data)){
$child = new Child();
$child->setFirstname($data['firstname']);
$child->setLastname($customInfosSecondStep["lastname"]);
$child->setUsername($customInfosSecondStep["email"]);
$child->setEmail($customInfosSecondStep["email"]);
$child->setIsVerified(true);
$child->setParentEmail($customInfosSecondStep["email"]); // replaced ??
$child->setRegistrationProfile($customInfosSecondStep["registrationProfile"]);
if (array_key_exists("isNewsletter",$customInfosSecondStep) && $customInfosSecondStep["isNewsletter"] == true){
$isNewsletter = true;
}else{
$isNewsletter = false;
}
$child->setIsNewsletter($isNewsletter);
$course = $this->em->getRepository(Course::class)->find($data['course']);
$serie = $this->em->getRepository(Serie::class)->findOneBySlug('generale');
$child->setCourse($course);
$child->setSerie($serie);
$child->setRoles(['ROLE_STUDENT']);
$child->setPassword($this->passwordHasher->hashPassword($child,$customInfosSecondStep["plainPassword"]["first"]));
$child->setEmailValidationToken(0);
$child->setEmailValidationTokenRequestedAt(new \DateTime('now'));
return $child;
}
return null;
}
public function processCheckout(Parents $parents,$stripeId = null, $withoutPayment = false)
{
$session = $this->requestStack->getSession();
$childInfos = $session->get('customInfos')["parents_registration"]['childrenForm'];
$slug = $session->get('customOffer');
$offer = $this->em->getRepository(Offer::class)->findOneBySlug($slug);
$i = 0;
$now = new \DateTime('now');
if (!empty($childInfos)) {
$this->em->persist($parents);
$this->em->flush();
if(!$withoutPayment && $offer->getCharge()){
$pp = new PaymentFutur();
$pp->setParents($parents);
$pp->setIntentPayment($stripeId);
$trial = clone $now;
$trial->modify('+8 day');
$pp->setDatePayment($trial);
$this->em->persist($pp);
$this->em->flush();
}
foreach ($childInfos as $infos) {
$summary = $this->requestStack->getSession()->get('summary');
$discount = null;
if (isset($summary[$i]['discount'])) {
$discount = $this->em->getRepository(Discount::class)->find($summary[$i]['discount']['id']);
}
if (!$withoutPayment) {
if ($summary[$i]['remise'] != 0 && 0 < $i) {
$title = $summary[$i]['remise'] == 20 ? 'lbp-rf-2' : 'lbp-rf-3';
$discount = $this->em->getRepository(Discount::class)->findOneByStripeId($title);
}
}
$child = $this->registrationStudent($infos);
$child->setParentEmail($parents->getEmail());
$this->em->persist($child);
$this->em->flush();
$SP = new StudentsParents();
$SP->setStudent($child);
$SP->setParents($parents);
$this->em->persist($SP);
$this->em->flush();
$sub = new Subscription();
$sub->setStudent($child);
$sub->setGuardiant($parents);
$sub->setOffer($offer);
$sub->setPrice(isset($summary[$i]['price']) ? $summary[$i]['price'] : $offer->getPrice());
$sub->setDiscount($discount);
$sub->setSubscripted($now);
if (!$withoutPayment) {
if (!$offer->getCharge()) {
$subscriptionStripe = $this->createSubscription($parents->getStripeId(), $discount);
$sub->setStripeId($subscriptionStripe["id"]);
} else {
!$withoutPayment ? $sub->setPaymentFutur($pp) : null;
$monthValid = $offer->getMonthValid();
if (is_numeric($monthValid)) {
$clone = clone $now;
$clone->modify('+8 day')->modify(sprintf('+%d months', $monthValid));
$sub->setUnSubscripted($clone);
}
}
} else {
$unSubscriptedDate = clone $now;
$monthValid = $offer->getMonthValid();
$monthValid ? $sub->setUnSubscripted($unSubscriptedDate->modify(sprintf('+%d months', $monthValid))) : null;
$discountAptar = $this->em->getRepository(Discount::class)->findOneByStripeId('aptar');
$sub->setDiscount($discountAptar);
$parents->setRoles(['ROLE_PARENTS']);
$child->addRoles(['ROLE_STUDENT']);
}
$sub->setBankStripe(true);
$sub->setByChecked(false);
$sub->setRenew(false);
$sub->setIsMobile(false);
$clone = clone $now;
$sub->setTrialDate(!$withoutPayment ? $clone->modify('+8 day') : null);
$this->em->persist($sub);
$this->em->flush();
$i++;
}
return true;
}
return false;
}
public function processCheckout2(Parents $parents,$paymentMethod,$paymentIntent)
{
$moreChildrenActive = false;
$session = $this->requestStack->getSession();
$allSubscrptionActive = $this->em->getRepository(Subscription::class)->getCurrentSubscriptionsByParent($parents);
if(count($allSubscrptionActive)>0){
$moreChildrenActive = true;
}
$childInfos = $session->get('customInfosSecondStep')["parents_registration_second_step"]['childrenForm'];
$slugOffer = $session->get('slugOffer');
$slugDiscount = $session->get('slugDiscount');
$discount = $pp = null;
$amount = 0;
$offer = $this->em->getRepository(Offer::class)->findOneBySlug($slugOffer);
$i = 0;
$now = new \DateTime('now');
$trial = clone $now;
$trial->modify('+7 day')->modify('-1 minutes');
if (!empty($childInfos) && $offer) {
if($offer->getCharge()){
$pp = new PaymentFutur();
$pp->setParents($parents);
$pp->setDatePayment($trial);
$this->em->persist($pp);
$this->em->flush();
}
foreach ($childInfos as $infos) {
$discount = $this->em->getRepository(Discount::class)->findOneByStripeId($slugDiscount);
$child = $this->registrationStudent($infos);
$child->setParentEmail($parents->getEmail());
$child->setRoles(['ROLE_STUDENT']);
if($offer->getTypeOffer() && $offer->getTypeOffer()->getSlug()=='visio'){
$child->setRoles(['ROLE_STUDENT','ROLE_MENTORAT']);
}
$this->em->persist($child);
$this->em->flush();
$SP = new StudentsParents();
$SP->setStudent($child);
$SP->setParents($parents);
$this->em->persist($SP);
$this->em->flush();
$sub = new Subscription();
$sub->setSubscripted($now);
$sub->setStudent($child);
$sub->setGuardiant($parents);
$sub->setOffer($offer);
if( $discount ){
if($i>0 || $moreChildrenActive){
$discount = $discount->getMoreChildReduce();
}
}else{
if($i>0 || $moreChildrenActive) {
$discount = $this->em->getRepository(Discount::class)->findOneByStripeId('remise50percent');
}
}
$sub->setDiscount($discount);
$sub->setPrice($sub->getAmount());
$sub->setTrialDate($trial);
if(!$offer->getCharge()){
$data = [
"customer" => $parents->getStripeId(),
"items" => [['price'=>$offer->getStripeId()]],
"trial_end"=> $trial->format('U'),
// "default_payment_method"=>$paymentMethod,
"collection_method"=>"charge_automatically",
"off_session"=> true,
"payment_settings"=>[
"payment_method_types"=>['sepa_debit', 'card'],
"save_default_payment_method"=>"on_subscription",
"payment_method_options"=>["card"=>["request_three_d_secure"=>"any"]]
]
];
if(!is_null($discount)){
$data = $discount?array_merge($data,['coupon' => strtoupper($discount->getStripeId())]):$data;
}
$subscriptionStripe = $this->stripeService->getStripeClient()->subscriptions->create($data);
$sub->setStripeId($subscriptionStripe["id"]);
}else{
if($offer->getSlug()=='bac-francais'){
$limit = \DateTime::createFromFormat('Y-m-d H:i:s', '2023-06-17 23:59:59');
$sub->setUnSubscripted($limit);
$sub->setPurchaseBacFrancaisAt($sub->getSubscripted());
}
}
$sub->setBankStripe(true);
$sub->setByChecked(false);
$sub->setRenew(false);
$sub->setIsMobile(false);
$sub->setPrice($offer->getPrice());
$sub->setPaymentFutur($pp);
$this->em->persist($sub);
$this->em->flush();
$i++;
if($offer->getSlug()=='bac-francais'){
$this->mailer->bacFrancaisConfirmationMail($parents,$child);
}
$amount+=$sub->getAmount();
}
if(!is_null($pp)){
$pp->setPrice($amount);
$this->em->flush();
}
return true;
}
return false;
}
public function checkCouponForFirstSubscription($coupon)
{
$data = $this->requestStack->getSession()->get('summary');
$one = $this->em->getRepository(Discount::class)->getDiscount(strtoupper($coupon));
if(!is_null($one) && $one->actif() && $one->getStripeId()){
$data[0]['discount']=[
'percent' =>$one->getPercent(),
'duration' => $one->getDuration(),
'durationInMonths'=> $one->getDurationInMonths(),
'id' => $one->getId(),
];
if(array_key_exists('price',$data[0])){
$data[0]['price'] = round($data[0]['price'] - $data[0]['price'] * $one->getPercent()/100,2);
}
$this->requestStack->getSession()->set('summary',$data);
$som = 0;
if(array_key_exists('price',$data[0])){
foreach ($data as $row){
$som+=$row['price'];
}
}
$offerIds = [];
if(!$one->getAllowOffer()->isEmpty()){
foreach ($one->getAllowOffer() as $offer){
$offerIds[]=$offer->getId();
}
}
return [
'code'=>$one->getStripeId(),
'percent'=>$one->getPercent(),
'percentMulti'=>$one->getMoreChildReduce()?$one->getMoreChildReduce()->getPercent():null,
'price'=>array_key_exists('price',$data[0])?$data[0]['price']:0,
'som'=>$som,
'description'=>is_null($one->getDescription())?$one->getTitle():$one->getDescription(),
'allowOffer'=>$offerIds
];
}
return false;
}
public function createSubscription($clientStripeId,$discount=null){
$session = $this->requestStack->getSession();
$slug = $session->get('customOffer');
$offer = $this->em->getRepository(Offer::class)->findOneBySlug($slug);
if($offer){
return $this->stripeService->createSubscriptionByData($clientStripeId,$offer->getStripeId(),[],true,$discount);
}
return false;
}
public function createSubscriptionEndEssaiGratuit($slug, $clientStripeId,$discount=null){
$offer = $this->em->getRepository(Offer::class)->findOneBySlug($slug);
if($offer){
// Trial FALSE
return $this->stripeService->createSubscriptionByData($clientStripeId,$offer->getStripeId(),[],false,$discount);
}
return false;
}
public function registerInfosTunnel($currentUser,$ritId = null){
$session = $this->requestStack->getSession();
if(!is_null($ritId)){
$rit = $this->em->getRepository(RegisterInfosTunnel::class)->find($ritId);
}else{
$rit = new RegisterInfosTunnel();
}
if($currentUser){
$rit->setCustomer($currentUser);
$rit->setEmailParents($currentUser->getEmail());
}else{
$parentsData = $this->registrationParentEssaiGratuit();
$parentsInfosData = ['firstname'=>$parentsData->getFirstname(),'lastname'=>$parentsData->getLastname(),'phone'=>$parentsData->getPhone()];
$rit->setInfosParents($parentsInfosData);
$rit->setEmailParents($parentsData->getEmail());
}
$slugOffer = $session->get('slugOffer');
$slugDiscount = $session->get('slugDiscount');
$offer = $this->em->getRepository(Offer::class)->findOneBySlug($slugOffer);
$coupon = $slugDiscount?$this->em->getRepository(Discount::class)->findOneByCodePromo($slugDiscount):null;
$rit->setOffer($offer);
$rit->setDiscount($coupon);
if(!$currentUser){
$infosChild = $session->get('customInfosSecondStep')["parents_registration_second_step"]['childrenForm'];
if(is_array($infosChild) && !empty($infosChild)){
$rit->setInfosChild($infosChild);
}
}
if(is_null($ritId)){
$this->em->persist($rit);
}
$this->em->flush();
return $rit;
}
}