<?php
declare(strict_types=1);
namespace App\Form\Extension;
use BitBag\SyliusOnePageCheckoutPlugin\Form\Type\CheckoutType;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormError;
use App\Entity\Order\Order;
use Sylius\Component\Shipping\Repository\ShippingMethodRepositoryInterface;
use App\Services\PPMCErpSynchroService;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Sylius\Component\Core\Model\AdjustmentInterface;
final class BitbagCheckoutExtension extends AbstractTypeExtension
{
private $shippingMethodRepository;
private $ppmcErpSynchroService;
private $container;
public function __construct(ShippingMethodRepositoryInterface $shippingMethodRepository, PPMCErpSynchroService $ppmcErpSynchroService, ContainerInterface $container)
{
$this->shippingMethodRepository = $shippingMethodRepository;
$this->ppmcErpSynchroService = $ppmcErpSynchroService;
$this->container = $container;
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('orderPickupSoColissimo', HiddenType::class, [
'required' => false,
])
->add('orderPickupShop', HiddenType::class, [
'required' => false
])
// ->addEventListener(FormEvents::, function (FormEvent $event) use ($options) {
// $data = $event->getData();
// dump($data);z
// // dump($data->getCustomer());
// // dump($data->getCustomer()->getDefaultAddress());
// // dump($data->getCustomer()->getDefaultAddress()->getCountryCode());
// // dump($data->getShippingAddress());
// // dump($data->getShippingAddress()->getCountryCode());
// // foreach($data->getCustomer()->getAddresses() as $ad){
// // dump($ad);
// // }
// // dump($data->getCustomer()->getShippingAddress());
// // dump($data->getCustomer());
// })
->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($options) {
$data = $event->getData();
$form = $event->getForm();
// dump($form);
dump($data);
// exit();
// echo 'icic';
//Soumission complète ?
if (isset($data['select_shipping'],
$data['select_shipping']['shipments'],
$data['address'])) {
//on envoie le formulaire complet, on check donc
if(isset($data['select_payment'],
$data['select_payment']['payments'])) {
//on ne peut pas payer par ici avec la carte cadeau
if($data['select_payment']['payments'][0]['method'] == 'KDO'){
$form->addError(new FormError(
"Vous ne pouvez pas payer en complément avec une carte cadeau"
));
}
}
$cart = $form->getNormData();
//On fait une valo de check final
$previousTotal = $cart->getTotal();
$process = new Process(['/usr/bin/php', $this->container->get('kernel')->getProjectDir().'/bin/console', 'ppmc:valorize-cart', '--cartId='.$cart->getId()]);
$process->setTimeout(3);
try {
$process->start();
$process->wait();
// echo $process->getOutput();
$em = $this->container->get('doctrine.orm.entity_manager');
$em->refresh($cart);
$cartItems = $cart->getItems();
foreach ($cartItems as $cartRow) {
$em->refresh($cartRow);
}
} catch (ProcessTimedOutException $exception) {
}
$currentTotal = $cart->getTotal();
if($previousTotal != $currentTotal) {
//La valorisation a évoluée, donc on a une erreur
//Promo plus valable par exemple etc...
$form->addError(new FormError(
"Votre panier a évolué, veuillez le vérifier avant de continuer. "
));
}
//On vérifie la carte cadeau si on essai d'en utiliser une
//On doit forcer la recharge des paiements car pas loadé dans l'objet
$payments = $cart->getPayments();
$adjustments = $cart->getAdjustments();
$this->container->get('doctrine')->getManager()->initializeObject($payments);
$this->container->get('doctrine')->getManager()->initializeObject($adjustments);
foreach($payments as $payment) {
$details = $payment->getDetails();
if(array_key_exists('giftCardCode', $details)) {
//On vérifie sa validité
$giftCard = $this->ppmcErpSynchroService->checkGiftCard(
$details['giftCardCode'],
$details['giftCardKey']
);
if($giftCard->getAmount()) {
$giftAmout = (int)($giftCard->getAmount()*100);
if($giftAmout < $payment->getAmount()) {
$form->addError(new FormError(
"Le montant de votre carte cadeau ne correspond pas au montant à payer, veuillez rééssayer.. "
));
$cart->removePayment($payment);
foreach($adjustments as $adjustement) {
$details = $adjustement->getDetails();
if($adjustement->getType() == AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT && array_key_exists('giftCardCode', $details)) {
$adjustement->unlock();
$cart->removeAdjustments(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
}
}
}
}
else {
$form->addError(new FormError(
"Votre carte cadeau n'est plus valide. "
));
$cart->removePayment($payment);
foreach($adjustments as $adjustement) {
$details = $adjustement->getDetails();
if($adjustement->getType() == AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT && array_key_exists('giftCardCode', $details)) {
$adjustement->unlock();
$cart->removeAdjustments(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
}
}
}
}
}
//On vérifie les ajustements au cas où (multi ajustements livraison notamment)
$hasShippingAdjustment = false;
foreach($adjustments as $adjustment) {
if($adjustment->getType() == AdjustmentInterface::SHIPPING_ADJUSTMENT) {
if($hasShippingAdjustment) {
$adjustement->unlock();
$cart->removeAdjustments(AdjustmentInterface::SHIPPING_ADJUSTMENT);
}
$hasShippingAdjustment = true;
}
}
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
}
if (isset($data['select_shipping'], $data['select_shipping']['shipments'])) {
if (count($data['select_shipping']['shipments']) > 0) {
// dump($data);
// dump($event);
if(isset( $data['select_shipping']['shipments'][1])){
$shippingMethod = $this->shippingMethodRepository->findOneBy([
'code' => $data['select_shipping']['shipments'][1]['method']
]);
}else{
$shippingMethod = $this->shippingMethodRepository->findOneBy([
'code' => $data['select_shipping']['shipments'][0]['method']
]);
}
$cart = $form->getNormData();
dump($cart);
if ($shippingMethod->getPickup() == 'so_colissimo') {
// Si c'est un point retrait type "so colissimo"
// Alors on vérifie que "orderPickupSoColissimo" n'est pas vide
if (isset($data['orderPickupSoColissimo']) && empty($data['orderPickupSoColissimo'])) {
$form->addError(new FormError(
"Vous devez selectionner un point retrait So Colissimo. "
. "Cliquez sur le mode de livraison pour selectionner un point retrait."
));
}
if(isset($data['address']['shippingAddress'])){
$firstName = $cart->getShippingAddress()->getFirstName();
$lastName = $cart->getShippingAddress()->getLastName();
$phoneNumber = $cart->getShippingAddress()->getPhoneNumber();
if(empty($firstName) || empty($lastName) || empty($phoneNumber) ){
$form->addError(new FormError(
"Vous devez renseigner les coordonnées de livraison. "
));
}
}
// dump($data);
} else if ($shippingMethod->getPickup() == 'shop') {
// Si c'est un point retrait type "retrait boutique"
// Alors on vérifie que "orderPickupShop" n'est pas vide
if (isset($data['orderPickupShop']) && empty($data['orderPickupShop'])) {
$form->addError(new FormError(
"Vous devez selectionner une boutique pour retirer vos articles. "
. "Cliquez sur le mode de livraison pour selectionner une boutique."
));
}
if(isset($data['address']['shippingAddress'])){
$firstName = $cart->getShippingAddress()->getFirstName();
$lastName = $cart->getShippingAddress()->getLastName();
$phoneNumber = $cart->getShippingAddress()->getPhoneNumber();
if(empty($firstName) || empty($lastName) || empty($phoneNumber) ){
$form->addError(new FormError(
"Vous devez renseigner les coordonnées de livraison. "
));
}
}
// dump($data);
} else if ($shippingMethod->getPickup() == 'apel') {
$cart = $form->getNormData();
// Si c'est un point retrait type "APEL"
// Alors on vérifie que "orderPickupShop" n'est pas vide
if (empty($cart->getApel())) {
$form->addError(new FormError(
"Vous devez selectionner une école pour retirer vos articles. "
. "Cliquez sur le mode de livraison pour selectionner une école."
));
}
if(isset($data['address']['shippingAddress'])){
$firstName = $cart->getShippingAddress()->getFirstName();
$lastName = $cart->getShippingAddress()->getLastName();
$phoneNumber = $cart->getShippingAddress()->getPhoneNumber();
if(empty($firstName) || empty($lastName) || empty($phoneNumber) ){
$form->addError(new FormError(
"Vous devez renseigner les coordonnées de livraison. "
));
}
}
// dump($data);
} else {
// Sinon on vide les champs
$data['orderPickupSoColissimo'] = '';
$data['orderPickupShop'] = '';
$event->setData($data);
}
}
}
else {
$data['orderPickupSoColissimo'] = $form->getNormData()->getOrderPickupSoColissimo();
$data['orderPickupShop'] = $form->getNormData()->getOrderPickupShop();
$event->setData($data);
}
dump($form);
// exit();
})
->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) use ($options) {
dump($event);
})
// ->addEventListener(FormEvents::PRE_SET_DATA , function (FormEvent $event) use ($options) {
// $data = $event->getData();
// // $form = $event->getForm();
// dump($data);
// if(empty($data->getShippingAddress())){
// $addresses = $data->getCustomer()->getAddresses();
// if(count($addresses) > 0){
// foreach($addresses as $address){
// // $newAddress = $this->container->get('sylius.factory.address')->createNew();
// // $newAddress->setFirstName($address->getFirstName());
// // $newAddress->setLastName($address->getLastName());
// // $newAddress->setCountryCode($address->getCountryCode());
// // $newAddress->setCity($address->getCity());
// // $newAddress->setStreet($address->getStreet());
// // $newAddress->setPostcode($address->getPostcode());
// // $newAddress->setPhoneNumber($address->getPhoneNumber());
// // $data->getCustomer()->addAddress($newAddress);
// $newAddress = clone $address;
// $newAddress->setCustomer($data->getCustomer());
// dump($newAddress);
// $this->container->get('doctrine')->getManager()->initializeObject($newAddress);
// $data->setBillingAddress($newAddress);
// $data->setShippingAddress($newAddress);
// $cartManager = $this->container->get('sylius.manager.order');
// $cartManager->persist($data);
// $cartManager->flush();
// $event->setData($data);
// dump($data);
// break;
// }
// }
// }else{
// // $address = $data->getShippingAddress();
// // dump($address);
// // foreach($data->getCustomer()->getAddresses() as $customerAddress){
// // if($customerAddress->getId() == $address->getId()){
// // $this->container->get('doctrine')->getManager()->initializeObject($customerAddress);
// // $data->setBillingAddress($customerAddress);
// // $data->setShippingAddress($customerAddress);
// // $cartManager = $this->container->get('sylius.manager.order');
// // $cartManager->persist($data);
// // $cartManager->flush();
// // $event->setData($data);
// // dump($data);
// // }
// // }
// }
// })
;
}
public static function getExtendedTypes(): iterable
{
return [CheckoutType::class];
}
}