<?php
namespace App\Controller;
use App\Form\EnrollFormType;
use App\Services\AttendeesService;
use App\Services\CheckwebsitesettingService;
use App\Services\GetPricesForMembershipService;
use App\Services\MailService;
use App\Services\MollieService;
use Carbon\Carbon;
use DateInterval;
use DateTime;
use Knp\Component\Pager\PaginatorInterface;
use Mollie\Api\Exceptions\ApiException;
use Mollie\Api\MollieApiClient;
use MultilingualBundle\Service\DocumentLookupService;
use Pimcore\Model\DataObject\Attendees;
use Pimcore\Model\DataObject\Campscourse;
use Pimcore\Model\DataObject\Order;
use Pimcore\Model\DataObject\Realisation;
use Pimcore\Model\DataObject\TypeCampscourse;
use Pimcore\Model\Document;
use Pimcore\Model\Notification\Service\NotificationService;
use Pimcore\Model\WebsiteSetting;
use Pimcore\Translation\Translator;
use Pimcore\Twig\Extension\Templating\PimcoreUrl;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class ServicesController extends BaseController
{
protected $checkwebsitesettingService;
protected $inotherlang;
protected $pimcoreUrl;
public function __construct(CheckwebsitesettingService $checkwebsitesettingService, DocumentLookupService $inotherlang, PimcoreUrl $pimcoreUrl)
{
$this->checkwebsitesettingService = $checkwebsitesettingService;
$this->inotherlang = $inotherlang;
$this->pimcoreUrl = $pimcoreUrl;
}
/**
*
* @param Request $request
* @return Response
*
*/
public function defaultAction(Request $request)
{
$documentID = $request->get('contentDocument')->getId();
$Infolinks = [];
if ($documentID !== null) {
$document = Document::getById($documentID);
if ($document->hasChildren()) {
$foldersLink = [];
$folders = $document->getChildren();
foreach ($folders as $folder) {
$pagesLink = [];
if ($folder->hasChildren()) {
$pages = $folder->getChildren();
foreach ($pages as $page) {
$pagesLink[] = [
'name_page' => $page->getProperties()['navigation_name']->getData(),
'link_page' => $page->getPath() . $page->getKey(),
];
}
}
$foldersLink[] = [
'name_folder' => $folder->getProperties()['navigation_name']->getData(),
'links' => $pagesLink,
];
}
$Infolinks = $foldersLink;
}
}
return $this->render('services/default.html.twig', [
'Infolinks' => $Infolinks,
]);
}
public function overviewAction(Request $request): Response
{
if ($this->document) {
if ($this->document->getEditable('typeCampscourse') && $this->document->getEditable('typeCampscourse')->getElementIds() !== []) {
foreach ($this->document->getEditable('typeCampscourse')->getElementIds() as $items) {
$ArrayTypeCampscourse = TypeCampscourse::getById($items['id'])?->getCampscourse();
$Campscourse = [];
foreach ($ArrayTypeCampscourse as $itemOject) {
$Campscourse[] = $itemOject;
}
}
usort($Campscourse, static function ($a, $b) {
return strtotime($a->getStart_date()) - strtotime($b->getStart_date());
});
return $this->render('services/overview.html.twig', [
'Campscourse' => $Campscourse
]);
}
}
return $this->render('services/overview.html.twig');
}
public function overviewALLAction(Request $request): Response
{
$Campscourse = Campscourse::getList();
$Campscourse->setOrderKey("start_date");
$Campscourse->setOrder("asc");
return $this->render('services/overview-all.html.twig', [
'Campscourse' => $Campscourse
]);
}
/**
* @Route("{_locale}/{path}/{key}~c{page}", name="campscourse-detail", defaults={"path"=""}, requirements={"path"=".*?", "key"="[\w-]+", "page"="\d+"})
*
* @param Request $request
*
* @return Response
* @throws \Exception
*/
public function detailAction(Request $request): Response
{
$campscourse = Campscourse::getById($request->get('page'));
if (!($campscourse instanceof Campscourse && ($campscourse->isPublished() || $this->verifyPreviewRequest($request, $campscourse)))) {
throw new NotFoundHttpException('Campscourse not found.');
}
$form = $this->createForm(EnrollFormType::class);
if (!$campscourse->getZeilofSurfKamp()) {
$form->remove('gezondheidmedische');
$form->remove('phoneNumber2');
$form->remove('zeilofsurfervaring');
}
$form->handleRequest($request);
$session = $request->getSession();
// Set a session variable
$lidkaartNumber = $session->get("lidkaart");
if ($form->isSubmitted() && $form->isValid()) {
if ($form->getData()['email'] === $form->getData()['confirmEmail']){
$attendees = AttendeesService::Create($form->getData(), $campscourse, $lidkaartNumber);
$session->remove("lidkaart");
$menberCard = new GetPricesForMembershipService();
$prices = $menberCard->getPrices();
//mollie
$mollie = new MollieService();
if (!$attendees->getLidformZSG()) {
$attendees->setAmount(number_format($campscourse->getPricePerPerson(), 2, '.', ''));
} else {
$attendees->setAmount(number_format($campscourse->getPricePerPerson() - $prices['wwsv_licentienummer_korting'], 2, '.', ''));
}
if ((float)$attendees->getAmount() > 0) {
$payment = $mollie->sendPayment($campscourse, $attendees, $this->pimcoreUrl, 'campscourse');
$attendees->setPaymentId($payment->id);
$attendees->save();
$response = new RedirectResponse($payment->getCheckoutUrl());
$response->send();
return $response;
} else {
// No Mollie payment needed, mark as paid
$attendees->setPayed(true);
$attendees->setDatePayment(\Carbon\Carbon::now());
$attendees->save();
return $this->redirectToRoute('thanks-page', [
'_locale' => $request->getLocale(),
'o' => $attendees->getId(),
]);
}
}
$this->addFlash('message', 'Email not the same');
}
return $this->render('services/detail.html.twig', [
'campscourse' => $campscourse,
'form' => $form->createView(),
]);
}
/**
* Checkpayment cart page
*
* @Route("{_locale}/payconnect/checkpayment", name="checkpayment-page")
*
* @param Request $request
* @return Response
* @throws \Exception
*/
public function checkpaymentAction(Request $request)
{
if ($request->isMethod('POST')) {
$mollie = new MollieService();
$attendees = Attendees::getById($request->get('id-pay', null));
$paymentId = $attendees->getPaymentId();
$response = $mollie->checkPayment($paymentId);
// Process response
if ($response) {
$payment = $response;
$this->sendNotificationFromOrder($payment, $attendees);
}
} else {
return $this->redirect("/" . $this->language);
}
return $this->redirect("/" . $this->language);
}
public function sendNotificationFromOrder($payment, $attendees)
{
try {
$order_id = $payment->metadata->order_id;
$invoicenumber = $payment->metadata->invoicenumber;
$campcourse_id = $payment->metadata->campcourse_id;
$paymentObject = Attendees::getById($order_id);
$orderIdPimcore = $paymentObject->getKey();
$keyattendees = $attendees->getKey();
if ($payment->isPaid() == TRUE && $paymentObject) {
if (!$paymentObject->getPayed()) {
$dateToday = \Carbon\Carbon::now();
$campcourse = Campscourse::getById($campcourse_id);
$paymentObject->setPayed(true);
$paymentObject->setDatePayment($dateToday);
$paymentObject->setPublished(true);
$paymentObject->save();
$mailData = [];
$mailData['order_id'] = $orderIdPimcore;
$mailData['email'] = $paymentObject->getEmailAddress();
$mailData['name'] = $paymentObject->getFirstname() . ' ' . $paymentObject->getLastname();
$mailData['lastname'] = $paymentObject->getLastname();
$mailData['firstname'] = $paymentObject->getFirstname();
$mailData['street'] = $paymentObject->getStreet();
$mailData['street_nr'] = $paymentObject->getStreetNumber();
$mailData['postcode'] = $paymentObject->getPostcode();
$mailData['place'] = $paymentObject->getPlace();
$mailData['country'] = $paymentObject->getCountry();
$mailData['phone'] = $paymentObject->getPhoneNumber();
$mailData['phone_2'] = $paymentObject->getPhonenumber1();
$mailData['gender'] = $paymentObject->getGender();
$mailData['birdt_date'] = $paymentObject->getBirthdate();
$mailData['note'] = $paymentObject->getNote();
$mailData['datum_order'] = $paymentObject->getDatePayment()?->format('d-m-Y');
$mailData['price_order'] = $paymentObject->getAmount();
$mailData['start_campcourse'] = $campcourse->getStart_date()?->format('d-m-Y');
$mailData['end_campcourse'] = $campcourse->getEnd_date()?->format('d-m-Y');
$mailData['invoicenumber'] = $campcourse->getTitle();
$emailTemplate = 'kamp-opleiding-mail-user';
$emailTemplateAdmin = 'kamp-opleiding-mail-club';
//send mail + Order voor bevestingen
if ($this->checkwebsitesettingService->check((string)$emailTemplate, "document")) {
$getEmailTemplate = \Pimcore\Model\WebsiteSetting::getByName((string)$emailTemplate);
$getEmailTemplateConfig = $getEmailTemplate->getData();
$emailDocument = $this->inotherlang->getLocalizedDocument($getEmailTemplateConfig, 'nl');
}
if ($this->checkwebsitesettingService->check((string)$emailTemplateAdmin, "document")) {
$getEmailTemplateAdmin = \Pimcore\Model\WebsiteSetting::getByName((string)$emailTemplateAdmin);
$getEmailTemplateConfigAdmin = $getEmailTemplateAdmin->getData();
$emailDocumentAdmin = $this->inotherlang->getLocalizedDocument($getEmailTemplateConfigAdmin, 'nl');
}
error_log(date('l jS \of F Y h:i:s A') . " Payment for $keyattendees succesfull paid \n", 3, PIMCORE_LOG_DIRECTORY . "/payments.log");
//send email to seller
if (!$paymentObject->getMailsend()) {
//send email to seller
(new \Pimcore\Mail())
->from('noreply@zsg.be')
->subject('Order : ' . $invoicenumber)
->setDocument($emailDocumentAdmin)
->setParams($mailData)
->send();
// send customer e-mail confirmation
(new \Pimcore\Mail())
->to($paymentObject->getEmailAddress())
->from('noreply@zsg.be')
->subject('Order : ' . $invoicenumber)
->setDocument($emailDocument)
->setParams($mailData)
->send();
$paymentObject->setMailsend(true);
$paymentObject->save();
}
$paymentObject->save();
}
} elseif ($payment->isOpen() == FALSE) {
//send email to seller
// $mailSeller = new MailService();
// $documentSalesNotpaid = $inotherlang->getLocalizedDocument($config->payment_notice);
// $mailSeller->setSubject($translator->trans("Order ").' '.$invoicenumber.' '.$translator->trans("is not paid"));
// $mailSeller->setDocument($documentSalesNotpaid);
// $mailSeller->setParams($mailData);
// $mailSeller->send();
/*
* The payment isn't paid and isn't open anymore. We can assume it was aborted.
*/
error_log(date('l jS \of F Y h:i:s A') . " Problem with $keyattendees, not paid \n", 3, PIMCORE_LOG_DIRECTORY . "/payments.log");
}
$paymentObject->save();
header('HTTP/1.1 200 OK');
die();
} catch (Mollie_API_Exception $e) {
echo "API call failed: " . htmlspecialchars($e->getMessage());
}
}
/**
* Redirectpayment cart page
*
* @Route("{_locale}/redirectpayment", name="redirectpayment-page")
*
* @param Request $request
* @return Response
* @throws \Exception
*/
public function redirectpaymentAction(Request $request, \Pimcore\Config\Config $websiteConfig)
{
if ($this->checkwebsitesettingService->check("payment_successfull", "document")) {
$paymentSuccesfullDocument = $websiteConfig->get('payment_successfull');
}
if ($paymentSuccesfullDocument) {
$language = $request->getLocale();
$paymentObject = $request->get('id-pay', null);
$returnAddress = $this->inotherlang->getLocalizedDocument($paymentSuccesfullDocument, "$language") . '?o=' . $paymentObject;
return $this->redirect($returnAddress);
}
}
/**
* Redirectpayment cart page
*
* @Route("{_locale}/bedankt", name="thanks-page")
*
* @param Request $request
* @return Response
* @throws \Exception
*/
public function redirectpaymentviewAction(Request $request)
{
if (!$this->editmode) {
$language = $request->getLocale();
$paymentItem = Attendees::getById($request->get('o', null));
if ($paymentItem) {
return $this->render('services/cart-redirect-payment.html.twig', [
'paymentItem' => $paymentItem
]);
} else {
return $this->redirect("/" . $language);
}
} else {
$paymentItem = null;
return $this->render('services/cart-redirect-payment.html.twig', [
'paymentItem' => $paymentItem
]);
}
}
}