<?php
declare(strict_types=1);
namespace App\Controller\Vignette;
use App\Controller\BaseController;
use App\Entity\Customer\Vehicle;
use App\Entity\VignetteInvoice\VignetteInvoice;
use App\Manager\BitbagStatic\BlockManager;
use App\Entity\Order\Order;
use App\Entity\Order\OrderItem;
use App\Entity\Vignette\Vignette;
use App\Entity\RoadAssistance\RoadAssistance;
use App\Events\VignetteEvent;
use App\Manager\CountryManager;
use App\Manager\Partner\PartnerManager;
use App\Manager\RoadAssistance\RoadAssistanceManager;
use App\Manager\Vignette\VignetteManager;
use App\Model\VignetteAvailabilityModel;
use App\Model\VignetteCategoryModel;
use App\Service\CustomerService;
use App\Service\InvoiceApiService;
use App\Service\InvoiceService;
use App\Service\ShoppingCartService;
use App\Service\StaticPagesBitbagService;
use App\Service\SystemService;
use App\Service\VignetteApiService;
use App\Service\VignetteOrderService;
use App\Validator\VignetteFormValidator;
use DateTime;
use Detection\MobileDetect;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;
use function Sentry\captureException;
final class VignetteController extends BaseController
{
const OP_ID = 1;
const REDIRECT_LOCALE_LIST = array('tr', 'bg', 'en', 'hu');
public function vignetteAction(Request $request, TranslatorInterface $translator): Response
{
$guid = $request->get('guid');
$renewRoVignetteVehicleId = $request->get('vehicleId');
$vehicle = null;
$oldVignette = null;
if (!empty($renewRoVignetteVehicleId)) {
$vehicle = $this->getEntityManager()->getRepository(Vehicle::class)->find($renewRoVignetteVehicleId);
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
if (!empty($vehicle) && $customer) {
$vehicle->setRoVignetteCategory(null);
if (empty($customer->getId()) || ($customer->getId() !== $vehicle->getCustomer()->getId())) {
$vehicle = null;
} else {
$oldVignette = $this->getEntityManager()->getRepository(Vignette::class)->findLatestConfirmedRoVignetteByRegistrationPlate($vehicle->getRegistrationPlate());
}
}
}
$desktopView = SystemService::checkDesktopView($request);
$render = '@templates/Front/vignette.html.twig';
if ($this->isMobile && !$desktopView) {
$render = '@templates/Mobile/vignette.html.twig';
}
/* $locale = $request->getLocale();
* if(!$this->getUser()) {
if ($locale !== 'ro'){
return $this->redirect('https://www.scala.ro/' . $locale . '/rovinieta');
}
}*/
$request->getSession()->remove('iframeSourceLink');
$vignetteCategories = (new VignetteCategoryModel($this->getEntityManager()))->getAllCategories();
return $this->render($render, [
'vignetteCategories' => $vignetteCategories,
'countries' => CountryManager::getActiveCountriesForRoVignette($this->getEntityManager()),
'guid' => $guid,
'vehicle' => $vehicle,
'oldValidFrom' => $oldVignette ? VignetteManager::retrieveRoVignetteOldValidUntil($oldVignette) : null,
'accordionBlocksAboutVignette' => StaticPagesBitbagService::getAllFilteredBlocks($this->getEntityManager(), BlockManager::BLOCK_ACCORDION_TEXT_VIGNETTE_CODE_PATTERN),
'vignetteKeywordsForSeo' => StaticPagesBitbagService::getFirstFilteredBlocks($this->getEntityManager(), BlockManager::BLOCK_SEO_META_VIGNETTE_KEYWORD_CODE_PATTERN),
'vignetteDescriptionForSeo' => StaticPagesBitbagService::getFirstFilteredBlocks($this->getEntityManager(), BlockManager::BLOCK_SEO_META_VIGNETTE_DESCRIPTION_CODE_PATTERN),
'roadAssistanceTranslations' => RoadAssistanceManager::getTranslationsForUI($translator)
]);
}
public function removeVignetteFromOrder(Request $request): Response
{
$serializer = $this->getContainer()->get('serializer');
$vignetteId = $request->get('vignetteId');
$vignetteRepository = $this->getDoctrine()->getRepository(Vignette::class);
$vignette = $vignetteRepository->find($vignetteId);
$order = $vignette->getOrder();
if ($order->getVignettes() && $order->getVignettes()->count() == 1) {
$response = $serializer->serialize(array('status' => 0, 'message' => 'Numarul minim de viniete ramase pe comanda trebuie sa fie mai mare ca 1 dupa stergere'), 'json');
return new Response($response);
}
$order->removeVignette($vignette);
$orderItem = $vignette->getOrderItem();
$this->getEntityManager()->getRepository(OrderItem::class)->deleteOrderItemById($orderItem->getId());
if ($sms = $vignette->getSms()) {
$smsOrderItem = $this->getEntityManager()->getRepository(OrderItem::class)->findOrderItemBySms($sms);
if ($smsOrderItem) {
$this->getEntityManager()->getRepository(OrderItem::class)->deleteOrderItemById($smsOrderItem->getId());
}
}
$this->getDoctrine()->getManager()->flush();
$order->recalculateItemsTotal();
$order->recalculateAdjustmentsTotal();
$this->getDoctrine()->getManager()->flush();
$response = $serializer->serialize(array('status' => 1, 'message' => 'success'), 'json');
return new Response($response);
}
public function loadVinBlock()
{
$template = json_encode('error');
try {
$template = $this->get('twig')
->render('@templates/Front/vignette/_vin_block.html.twig');
$detect = new MobileDetect();
if ($detect->isMobile()) {
$template = $this->get('twig')
->render('@templates/Mobile/vignette/_vin_block.html.twig');
}
} catch (\Throwable $exception) {
captureException($exception);
}
return new Response($template);
}
public function previewVignettesData(Request $request)
{
$response = json_encode('fail');
$serializer = $this->getContainer()->get('serializer');
$params = $request->request->all();
$orderId = $params['orderId'];
if ($orderId == null) {
$response = $serializer->serialize('id comanda gol', 'json');
return new Response($response);
}
$orderRepository = $this->getDoctrine()->getRepository(Order::class);
$order = $orderRepository->find($orderId);
$customer = $order->getCustomer();
$vignettes = $order->getVignettes();
foreach ($vignettes as $key => $vignette) {
$validFrom = $params['pick_date_op' . $key];
$validFromDateTime = new DateTime($validFrom);
$vignette->setValidFrom($validFromDateTime);
$validUntil = new DateTime();
switch ($vignette->getAvailability()->getName()) {
case '1 zi':
$validUntil = date('Y-m-d 23:59:59',strtotime($validFrom));
break;
case '7 zile':
$validUntil = date('Y-m-d 23:59:59',strtotime($validFrom . ' + 6 days'));
break;
case '30 zile':
$validUntil = date('Y-m-d 23:59:59', strtotime($validFrom . ' + 29 days'));
break;
case '90 zile':
$validUntil = date('Y-m-d 23:59:59', strtotime($validFrom . ' + 89 days'));
break;
case '12 luni':
$validUntil = date('Y-m-d 23:59:59', strtotime($validFrom . ' + 364 days'));
break;
default:
break;
}
$validUntilDateTime = new DateTime($validUntil);
$vignette->setValidUntil($validUntilDateTime);
}
$vignettesApi = VignetteApiService::getVignettesForInvoiceApi($vignettes);
$result = InvoiceApiService::previewData($customer, $vignettesApi);
$result = json_decode($result);
if (isset($result->dload_url) && $result->dload_url) {
$response = json_encode($result->dload_url);
}
return new Response($response);
}
public function getAvailabilitiesByCategoryAction(Request $request): Response
{
$id = $request->get('id');
$availabilities = null;
if ($id != null) {
$availabilities = (new VignetteAvailabilityModel($this->getEntityManager()))
->getAvailabilityForCategoryId($id);
$serializer = $this->getSerializer();
$availabilities = $serializer->serialize($availabilities, 'json');
}
return new Response($availabilities);
}
public function vignetteFormSubmitAction(Request $request): Response
{
$session = $request->getSession();
$validator = new VignetteFormValidator($this->getEntityManager(), $this->getSerializer());
$request->request->set('validFrom', str_replace('-', '/', $request->get('validFrom')));
$errors = null;
if ($validator->checkForm($request)) {
$errors = json_encode(array('success' => 1));
} else {
if ($session->has('vignetteErrors')) {
$errors = $session->get('vignetteErrors');
}
}
$session->set('previousUrl', 'rovinieta');
return new Response($errors);
}
public function vignetteFormSubmitApi(Request $request, TranslatorInterface $translator): Response
{
$response = null;
$isRovinietaIframe = $request->get('rovinietaIframe');
$request->request->set('validFrom', str_replace('-', '/', $request->get('validFrom')));
$validRegistrationNumber = VignetteOrderService::checkIfVignetteIsAlreadyInCart($request, $this->getEntityManager());
if ($isRovinietaIframe && !$validRegistrationNumber) {
//clear cart
if (ShoppingCartService::removeVignetteFromCartByRegistrationPlate($request)){
$validRegistrationNumber = true;
}
}
if ($validRegistrationNumber) {
$vignetteEvent = new VignetteEvent();
$this->dispatcher->addListener('check.vignette', function (VignetteEvent $event) {
$event->stopPropagation();
});
$this->dispatcher->dispatch($vignetteEvent, VignetteEvent::CHECK_VIGNETTE);
if ($vignetteEvent->isPropagationStopped()) {
if ($request->request->has('vignetteSubmitForm')
&& $request->request->get('vignetteSubmitForm') == 1) {
$response = json_encode(array('success' => true));
if (RoadAssistanceManager::isVehicleEligibleForRoadAssistance($request->request->all())
&& !RoadAssistanceManager::haveAnActiveRoadAssistanceForRegistrationPlate($request, $this->getEntityManager())) {
$roadAssistanceService = $this->getContainer()->get('app.service.road_assistance.road_assistance');
$roadAssistanceResponse = $roadAssistanceService->storeNewRoadAssistanceInCart(RoadAssistance::FLAG_SOURCE_EXTRA_OPTION);
if (!$roadAssistanceResponse['success']) {
if ($roadAssistanceResponse['errorCode']) {
$this->addFlash('error', SystemService::retrieveMessage($roadAssistanceResponse['errorCode'], $translator));
}
}
}
} elseif ($request->request->has('specialErrors')) {
$vignetteApiError = $request->request->get('specialErrors');
$response = json_encode(array('vignetteApiError' => $vignetteApiError));
}
}
} else {
$vignetteApiError = array('alreadyInCart' => 'Already in cart');
$apiStatusCode = 400;
$response = json_encode(array('vignetteApiError' => $vignetteApiError, 'apiStatusCode' => $apiStatusCode));
}
return new Response($response);
}
public function getMonth(Request $request, TranslatorInterface $translator): Response
{
$monthNumber = $request->get('month_number');
$locale = $request->get('locale');
$monthName = null;
if ($monthNumber != null) {
$translationMonthKey = 'app.ui.month_' . $monthNumber;
$monthName = $translator->trans($translationMonthKey, [], null, $locale);
$serializer = $this->getSerializer();
$monthName = $serializer->serialize($monthName, 'json');
}
return new Response($monthName);
}
public function roVignetteIframe(Request $request, TranslatorInterface $translator)
{
$partnerService = $this->getContainer()->get('app.service.partner.partner');
$partnerService->verifyToken($request, PartnerManager::CAN_ISSUE_RO_VIGNETTE_INDEX);
$token['partnerPublicToken'] = $request->get(PartnerManager::SESSION_PARTNER_PUBLIC_TOKEN_NAME);
$request->getSession()->set('iframeSourceLink', $this->generateUrl('app_shop_ro_vignette_iframe', $token));
$partner = $partnerService->retrievePartner($request->get('partnerPublicToken'));
$hasAlertSms = ($partner->getRole())->getCanAlertSms();
$canIssueRoadAssistance = ($partner->getRole())->getCanIssueRoadAssistance();
$guid = $request->get('guid');
$desktopView = SystemService::checkDesktopView($request);
$render = '@templates/Front/vignette/iframe.html.twig';
if ($this->isMobile && !$desktopView) {
$render = '@templates/Mobile/vignette/iframe.html.twig';
}
$vignetteCategories = (new VignetteCategoryModel($this->getEntityManager()))->getAllCategories();
PartnerManager::checkQRCodeFlow($request);
return $this->render($render, [
'vignetteCategories' => $vignetteCategories,
'countries' => CountryManager::getActiveCountriesForRoVignette($this->getEntityManager()),
'guid' => $guid,
'hasAlertSms' => $hasAlertSms,
'canIssueRoadAssistance' => $canIssueRoadAssistance,
'accordionBlocksAboutVignette' => StaticPagesBitbagService::getAllFilteredBlocks($this->getEntityManager(), BlockManager::BLOCK_ACCORDION_TEXT_VIGNETTE_CODE_PATTERN),
'vignetteKeywordsForSeo' => StaticPagesBitbagService::getFirstFilteredBlocks($this->getEntityManager(), BlockManager::BLOCK_SEO_META_VIGNETTE_KEYWORD_CODE_PATTERN),
'vignetteDescriptionForSeo' => StaticPagesBitbagService::getFirstFilteredBlocks($this->getEntityManager(), BlockManager::BLOCK_SEO_META_VIGNETTE_DESCRIPTION_CODE_PATTERN),
'roadAssistanceTranslations' => RoadAssistanceManager::getTranslationsForUI($translator),
'publicToken' => $partner->getPublicToken()
]);
}
public function showVignettePolicyForPartner(Request $request)
{
$response = new Response(json_encode(array('status' => 0)));
$invoice = $this->getDoctrine()->getRepository(VignetteInvoice::class)->findOneBy(array('order' => base64_decode($request->get('order_id'))));
if ($invoice) {
$apiInvoiceService = new InvoiceApiService();
$apiInvoiceService->getPdfByInvoice($invoice);
if ( $response = $apiInvoiceService->getLastResponse()) {
$response = json_decode($response);
if ($response->invoice_id > 0) {
$url = $response->dload_url;
$filename = 'Factura';
InvoiceService::openPdf($url, $filename);
$response = new Response(json_encode(array('status' => 1)));
}
}
}
return $response;
}
}