<?php
namespace App\Controller;
use App\Entity\Currency;
use App\Entity\PageCategory;
use App\Entity\Setting;
use App\Service\WebticariClient;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Query;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\Serializer;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Tests\DependencyInjection\Fixtures\UserProvider\DummyProvider;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use App\Entity\Cart;
use App\Entity\Category;
use App\Entity\Menu;
use App\Entity\Page;
use App\Entity\Store;
use App\Entity\User;
use App\Entity\UserComment;
use App\Entity\UserSettings;
use App\Entity\UserWishlist;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
abstract class BaseController extends AbstractController
{
private $state = [];
private $firstPageIsLogin;
protected $requestStack;
/**
* @var Serializer
*/
private $serializer;
/**
* @var WebticariClient
*/
private $webticariClient;
/**
* BaseController constructor.
* @param Serializer $serializer
* @param EntityManager $em
* @param WebticariClient $webticariClient
*/
public function __construct(Serializer $serializer, EntityManager $em, webticariClient $webticariClient,RequestStack $requestStack)
{
$this->serializer = $serializer;
$this->webticariClient = $webticariClient;
$this->requestStack = $requestStack;
}
protected function serialize($data, $format = 'json')
{
$context = new SerializationContext();
$groups[] = 'Default';
$context->setGroups($groups);
return $this->serializer->serialize($data, $format, $context);
}
protected function normalize($data, $format = 'json')
{
$context = new SerializationContext();
$groups[] = 'Default';
$context->setGroups($groups);
return $this->serializer->toArray($data, $context);
}
protected function setState($key, $value)
{
$this->state[$key] = $value;
}
protected function pushState($state)
{
$this->state = array_merge($this->state, $state);
}
protected function response(string $view, $data = [], $headers = []): Response
{
$response = new Response();
$request = $this->get('request_stack')->getCurrentRequest();
$accessAllowedRoutes = [
'catalog_page',
'catalog_dealership_form',
'catalog_checkout_pay',
'catalog_checkout_summary',
'catalog_checkout_address', 'catalog_payment',
'catalog_payment_success',
'catalog_payment_error',
'wishlist'
];
if ($this->firstPageIsLogin && !$this->isGranted('ROLE_USER') && !in_array($request->attributes->get('_route'), $accessAllowedRoutes)) {
throw new AuthenticationException();
}
$cartCookie = $request->cookies->get('CART_ID');
$firstCookieArray = [];
if($request->cookies->get('device_view') == 'full'){
$firstCookie = $request->cookies->get('FIRST');
$firstCookieArray[0] = $firstCookie;
}else {
$firstCookieArray[0] =1;
}
$this->setState('firstCookie', [
'items' => $firstCookieArray
]);
// $denemeArray = $this->state;
// dump($denemeArray['firstCookie']['items'][0]);
if ($cartCookie === null) {
$date = new \DateTime();
$date->add(new \DateInterval('P10Y'));
// $cookie = new Cookie('CART_ID', $this->getSession()->getId(), $date, '/', null, true, true, false, 'None');
$cookie = new Cookie('CART_ID', $this->getSession()->getId(), $date, '/', null, false, true, false, null);
$response->headers->setCookie($cookie);
}
$response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '-1');
foreach ($headers as $key => $value) {
$response->headers->set($key, $value);
}
$currencies = $this->getCurrencies();
$this->setState('currency', $currencies);
$favicon = $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'favicon']);
$this->setState('favicon', $favicon->getValue());
$data['favicon'] = $favicon->getValue();
$wplocation = $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'wpDestekButonYonu']);
if ($wplocation == !null) {
$this->setState('wplocation', $wplocation->getValue());
$data['wplocation'] = $wplocation->getValue();
} else {
$this->setState('wplocation', "0");
$data['wplocation'] = "0";
}
$translationsTr = __DIR__ . '/../../translations/catalog.tr.yaml';
$translationsEn = __DIR__ . '/../../translations/catalog.en.yaml';
$parsedTranslationsTr = Yaml::parse(file_get_contents($translationsTr));
$parsedTranslationsEn = Yaml::parse(file_get_contents($translationsEn));
$this->setState('translate', [
'activeLocale' => $request->getLocale(),
'languages' => [
'tr' => $parsedTranslationsTr,
'en' => $parsedTranslationsEn
]
]);
$this->setState('cart', $this->getCart());
$this->setState('deneme', $this->getCart());
$this->setState('address', $this->getAddresses());
$this->setState('wishlist', $this->getWishlist());
$this->setState('accountInfo', $this->getAccountInfo());
$this->setState('comment', $this->getComments());
$this->setState('commentByUser', $this->getCommentItemsByUser());
// $this->setState('campaignProduct', $this->getCampaignProduct());
$store = $this->getDoctrine()->getRepository(Store::class)->find(1);
$this->setState('store', $store);
if($this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'ucretsizKargoSecenek'])){
$ucretsizKargoSecenek = $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'ucretsizKargoSecenek']);
$ucretsizKargoMiktar = $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'ucretsizKargoMiktar']);
}else{$ucretsizKargoSecenek =null;
$ucretsizKargoMiktar =null;
}
$themeColor = $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'theme-color']);
$themeHoverColor = $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'theme-color-2']);
$this->setState('route', [
'cart' => $this->generateUrl('catalog_cart'),
'backToShop' => $this->generateUrl('catalog_search'),
'login' => $this->generateUrl('app_login'),
'checkout' => [
'cart' => $this->generateUrl('catalog_checkout_cart'),
'payment' => $this->generateUrl('catalog_checkout_pay'),
'summary' => $this->generateUrl('catalog_checkout_summary'),
'address' => $this->generateUrl('catalog_checkout_address'),
],
]);
$explodedMetaTagsArray = explode('ç', $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'metatags'])
->getValue());
$lastMetaTags = [];
foreach ($explodedMetaTagsArray as $metatags) {
$metatags = html_entity_decode($metatags);
// $metatags = htmlentities($metatags);
array_push($lastMetaTags, $metatags);
};
// $data['fb_id'] = $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'fb_id'])
// ->getValue();
$data['pagec'] = $this->getDoctrine()->getRepository(Page::class)->createQueryBuilder('page')->orderBy('page.id', 'DESC')->getQuery()->getResult();
$data['mainPageCategories'] = $this->getDoctrine()
->getRepository(PageCategory::class)
->createQueryBuilder('category')
->orderBy('category.id', 'ASC')
->getQuery()
->getResult();
$data['mainCategories'] = $this->getDoctrine()->getRepository(Category::class)->findAllCategories();
$data['metaTags'] = $lastMetaTags;
$data['ucretsizKargoSecenek'] = $ucretsizKargoSecenek;
$data['ucretsizKargoMiktar'] = $ucretsizKargoMiktar;
$data['themeColor'] = $themeColor;
$data['themeHoverColor'] = $themeHoverColor;
$data['isAuthenticated'] = $this->isGranted('ROLE_USER');
$data['currency'] = $currencies;
$data['salesRepresentative'] = null;
$data['user'] = null;
$array =$this->getDoctrine()
->getRepository(Menu::class)
->createQueryBuilder('menu')
->orderBy('menu.sortStatus', 'ASC')
->getQuery()
->getResult();
$array2=[];
foreach ($array as $menu){
if($menu->getPage()!=null){
array_push($array2,[
'type' => 0,
'sortStatus'=> $menu->getSortStatus(),
'url' => $menu->getPage()->getSeo() ? 'sayfalar/'.$menu->getPage()->getSeo() :'',
'name' => $menu->getPage()->getTitle(),
'category'=>null,
'childStatus'=>null,
]);
}
else if($menu->getCategory()!=null) {
array_push($array2,[
'type' => 1,
'sortStatus'=> $menu->getSortStatus(),
'url' => '',
'name' => null,
'category'=>$menu->getCategory(),
'childStatus'=>$menu->getChildStatus(),
]);
}
else{
array_push($array2,[
'type' => 0,
'sortStatus'=> $menu->getSortStatus(),
'url' => $menu->getUrl() ?$menu->getUrl() : '' ,
'name' => $menu->getName(),
'category'=>null,
'childStatus'=>null,
]);
}
}
// dump($array2);
$data['menu'] = $array2;
if ($this->getUser()) {
$user = $this->getDoctrine()->getRepository(User::class)->find($this->getUser()->getId());
$this->setState('customerBranchState', [
'branches' => $user ? $user->getCustomerBranches() : [],
'branch' => $this->getSession()->get('branch')
]
);
$data['salesRepresentative'] = $user ? $user->getSalesRepresentative() : null;
$data['user'] = $user;
}
$settings = $this->getDoctrine()->getRepository(Setting::class)->findAll();
$settingState = [];
$privateSettings = [
'baslik',
'imza',
'kulad',
'mailadres',
'popauth',
'popport',
'popserverad',
'popssl',
'port',
'serverad',
'sifre',
'smtpauth',
'smtpssl'
];
foreach ($settings as $setting) {
if (!in_array($setting->getKey(), $privateSettings)) {
$settingState[$setting->getKey()] = (string)$setting->getValue();
}
}
$settingState['showPriceStatus'] = $data['user'] !== null ? "1" : ($settingState['showPriceStatus'] == "0" ? "0" : "1");
$topHeaderInfo = isset($settingState['topHeaderInfo']) ? explode(',', $settingState['topHeaderInfo']) : [];
$data['topHeaderInfo'] = [
'salesRepresentativeName' => in_array('salesRepresentativeName', $topHeaderInfo) && $data['salesRepresentative'] ? $data['salesRepresentative']->getName() : null,
'salesRepresentativePhone' => in_array('salesRepresentativePhone', $topHeaderInfo) && $data['salesRepresentative'] ? $data['salesRepresentative']->getPhone() : null,
'salesRepresentativeEmail' => in_array('salesRepresentativeEmail', $topHeaderInfo) && $data['salesRepresentative'] ? $data['salesRepresentative']->getEmail() : null,
'customerName' => in_array('customerName', $topHeaderInfo) && $data['user'] ? $data['user']->getName() : null,
'customerBalance' => in_array('customerBalance', $topHeaderInfo) && $this->getSession()->get('customerInformation') ? $this->getSession()->get('customerInformation')['balance'] : null,
'customerCurrency' => in_array('customerBalance', $topHeaderInfo) && $this->getSession()->get('customerInformation') ? $this->getSession()->get('customerInformation')['currency'] : null,
];
$this->setState('settingState', $settingState);
$data['searchQuery'] = $request->query->has('q') ? $request->query->get('q') : '';
$data['searchCategory'] = 0;
if ($request->query->has('category')) {
$category = explode('_', $request->query->get('category'));
$data['searchCategory'] = $category[0];
}
$data['store'] = $this->getDoctrine()->getRepository(Store::class)->find(1);
$data['setting'] = $settingState;
return $this->render($view, array_merge(['state' => $this->serialize($this->state)], $data), $response);
}
public function getSession()
{
if (null === $this->requestStack) {
throw new \LogicException('RequestStack is null.');
}
return $this->requestStack->getSession();
}
private function getCurrencies(): array
{
$currencies = new ArrayCollection($this->getDoctrine()->getRepository(Currency::class)->findAll());
$getDefaultCurrencySetting = $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'defaultCurrency']);
$defaultCurrencySetting = $getDefaultCurrencySetting ? ($getDefaultCurrencySetting->getValue() === 'Customer' ? null : $getDefaultCurrencySetting->getValue()) : null;
$session = $this->getSession();
$defaultCurrency = null;
if ($this->getUser() !== null && $defaultCurrencySetting === null) {
$user = $this->getUser();
$defaultCurrency = $currencies->filter(static function (Currency $currency) use ($user) {
return $currency->getCode() === $user->getCurrency();
})->first();
} else if ($this->getUser() !== null && $defaultCurrencySetting !== null) {
$defaultCurrency = $currencies->filter(static function (Currency $currency) use ($defaultCurrencySetting) {
return $currency->getCode() === $defaultCurrencySetting;
})->first();
} else if ($this->getUser() === null) {
$defaultCurrency = $defaultCurrencySetting !== null ? $currencies->filter(static function (Currency $currency) use ($defaultCurrencySetting) {
return $currency->getCode() === $defaultCurrencySetting;
})->first() : $currencies[0];
}
if ($session->get('defaultCurrency') === null) {
$session->set('defaultCurrency', $defaultCurrency);
}
return [
'currencies' => $currencies,
'defaultCurrency' => $session->get('defaultCurrency', $defaultCurrency),
'userCurrency' => $defaultCurrency,
];
}
private function getCart(): array
{
if ($this->getUser()) {
$cartItems = $this->getDoctrine()->getRepository(Cart::class)->findCartItemsByUser($this->getUser());
} else {
$cartCookie = $this->get('request_stack')->getCurrentRequest()->cookies->get('CART_ID');
$cartItems = $this->getDoctrine()->getRepository(Cart::class)->findCartItemsByCookie($cartCookie);
}
return [
'items' => $cartItems
];
}
private function getAddresses(): array
{
if ($this->getUser()) {
$user = $this->getDoctrine()->getRepository(User::class)->find($this->getUser()->getId());
$userX = $user->getId();
$em = $this->getDoctrine()->getManager();
$result = $em->createQuery('select m from App:UserAddress m where m.userControl = ' . $userX . ' ')
->getResult(Query::HYDRATE_ARRAY);
} else {
$result = [];
}
return [
'items' => $result
];
}
private function getWishlist(): array
{
if ($this->getUser()) {
$user = $this->getDoctrine()->getRepository(User::class)->find($this->getUser()->getId());
$userX = $user->getId();
$em = $this->getDoctrine()->getManager();
$wishlistItems = $this->getDoctrine()->getRepository(UserWishlist::class)->findWishlistItemsByUser
($this->getUser());
} else {
$wishlistItems = [];
}
return [
'items' => $wishlistItems
];
}
private function getAccountInfo(): array
{
if ($this->getUser()) {
$user = $this->getDoctrine()->getRepository(User::class)->find($this->getUser()->getId());
$usersettingcontrol = $this->getDoctrine()->getRepository(UserSettings::class)->findOneBy(['user' => $user->getId()]);
} else {
$usersettingcontrol = [];
}
return [
'items' => $usersettingcontrol
];
}
private function getComments(): array
{
$result = $this->getDoctrine()->getRepository(UserComment::class)->findAll();
return [
'items' => $result
];
}
// private function getCampaignProduct(): array
// {
// $campaignProductItems = $this->getDoctrine()->getRepository('App:Product')
// ->findAll();
//
// return [
// 'items' => $campaignProductItems
// ];
// }
private function getCommentItemsByUser(): array
{
if ($this->getUser()) {
$user = $this->getDoctrine()->getRepository(User::class)->find($this->getUser()->getId());
$userX = $user->getId();
$em = $this->getDoctrine()->getManager();
$commentItems = $this->getDoctrine()->getRepository(UserComment::class)->findCommentItemsByUser
($this->getUser());
} else {
$commentItems = [];
}
return [
'items' => $commentItems
];
}
}