<?php
namespace App\Controller;
use App\Entity\Basket;
use App\Entity\Basketitem;
use App\Entity\Chilidocument;
use App\Entity\Delivery;
use App\Entity\Discountcode;
use App\Service\LogService;
use Detection\MobileDetect;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Csrf\CsrfTokenManager;
class BasketController extends AbstractController
{
private $csrfToken;
public function __construct() {
$csrfToken = new CsrfTokenManager();
$this->csrfToken = $csrfToken->getToken('access');
}
public function getCurrentBasket() {
$basketcookie = getBasketCookie();
$em = $this->getDoctrine()->getManager();
if ($this->getUser()) {
$basket = $em->getRepository(Basket::class)->findBy(['user' => $this->getUser()->getId(), 'is_order' => false]);
} else {
$basket = $em->getRepository(Basket::class)->findBy(['csrftoken' => $basketcookie, 'is_order' => false]);
}
if ($basket) {
$basket = $basket[0];
} else {
$basket = new Basket();
}
// Check for duplicates and clean up
// Make sure basket items is attached to correct basket
return $basket;
}
public function getNumberOfCurrentBasketItems() {
$number_of_basketitems = 0;
$basket = $this->getCurrentBasket();
if ($basket != null) {
if ($basket->getId() != null) {
$number_of_basketitems = $basket->getBasketitems()->count();
}
}
return new JsonResponse(array('num' => $number_of_basketitems));
}
private function getChilidocumentDefaultAmount($id) {
$product = $this->getDoctrine()->getRepository(Chilidocument::class)->find($id);
$product_price = $product->getPrice();
while ($product_price === null) {
$product = $this->getDoctrine()->getRepository(Chilidocument::class)->findOneBy(['path' => $product->getMother()]);
$product_price = $product->getPrice();
}
return $product_price->getDefaultAmount();
}
private function getChilidocumentPrice($id,$amount) {
$product = $this->getDoctrine()->getRepository(Chilidocument::class)->find($id);
$product_price = $product->getPrice();
while ($product_price === null) {
$product = $this->getDoctrine()->getRepository(Chilidocument::class)->findOneBy(['path' => $product->getMother()]);
$product_price = $product->getPrice();
}
switch ($product_price->getType()) {
case 'levels':
$price_amount = $product_price->getPriceAmount();
$price_amount = json_decode($price_amount,1);
$price = 0;
foreach ($price_amount as $qty => $prc) {
if ($amount >= $qty) {
$price = $prc;
}
}
break;
case 'arbitrary':
$price_amount = $product_price->getPriceAmount();
$price_amount = json_decode($price_amount,1);
$price = 0;
foreach ($price_amount as $qty => $prc) {
if ($amount >= $qty) {
$price = $prc;
}
}
break;
}
return $price;
}
private function getBasketWeight($basket) {
$w = 0;
foreach($basket->getBasketitems() as $bi) {
$w = ($w + ($bi->getAmount() * $bi->getChilidocument()->getWeight()));
}
return $w;
}
private function clarifyDelivery($basket) {
$em = $this->getDoctrine()->getManager();
$conn = $em->getConnection();
$totalWeight = $this->getBasketWeight($basket);
$sql = 'select * from delivery where weightlimit = 0 or weightlimit > ' . $totalWeight . ' order by is_default desc,sortorder asc';
$sta = $conn->prepare($sql);
// dd($sta);
// $sta = $em->getConnection()->prepare($sql);
// $sta->execute();
$execute = $sta->executeQuery();
$deliveries = $execute->fetchAllAssociative();
# dd($deliveries);
if ($basket->getDelivery() == null) {
$default_delivery = $em->getRepository(Delivery::class)->findOneBy(['id' => $deliveries[0]['id']]);
$basket->setDelivery($default_delivery);
$em->persist($basket);
$em->flush();
}
return $deliveries;
}
/**
* @Route("/Handlekurv", name="Handlekurv")
*/
public function Handlekurv(Session $session, LogService $log): Response
{
$log->addLog('info','Open basket');
$browser_width = $session->get('browserwidth');
#dd($browser_width);
if ($browser_width == null) {
return $this->redirectToRoute('setbrowserwidth_page');
}
$basketcookie = getBasketCookie();
$basket = $this->getCurrentBasket();
$delivery = $this->clarifyDelivery($basket);
return $this->render('theme_' . config_theme . '/basket.html.twig', [
'basketcookie' => $basketcookie,
'basket' => $basket,
'width' => $browser_width,
'stripe_pk' => config_stripe_Publishable_key,
'delivery' => $delivery,
]);
}
/**
* @Route("/saveChilidocumentToBasket", name="saveChilidocumentToBasket")
*/
public function saveChilidocumentToBasket(): Response
{
$em = $this->getDoctrine()->getManager();
$post = $_REQUEST;
#pre($post,1);
$doc_id = $post['chilidocument_id'];
$basket = $this->getCurrentBasket();
if ($basket->getId() == null) {
if ($this->getUser()) $basket->setUser($this->getUser());
$basket->setCsrftoken(getBasketCookie());
$basket->setIsOrder(false);
$em->persist($basket);
$em->flush();
}
$chilidocument = $em->getRepository(Chilidocument::class)->find($doc_id);
$default_amount = $this->getChilidocumentDefaultAmount($doc_id);
$price = $this->getChilidocumentPrice($doc_id,$default_amount);
$basket_item = $em->getRepository(Basketitem::class)->findBy(['basket' => $basket,'chilidocument' => $chilidocument]);
if (!$basket_item) {
$new_basketitem = new Basketitem();
$new_basketitem->setBasket($basket);
$new_basketitem->setIsChili(true);
$new_basketitem->setIsPhysical(false);
$new_basketitem->setChilidocument($chilidocument);
$new_basketitem->setChiliXml($post['chili_xml']);
$new_basketitem->setAmount($default_amount);
$new_basketitem->setPrice($price);
$em->persist($new_basketitem);
$em->flush();
$save_type = 'Create';
} else {
$basket_item = $basket_item[0];
$basket_item->setChiliXml($post['chili_xml']);
$em->persist($basket_item);
$em->flush();
$save_type = 'Update';
}
return new JsonResponse(array('status' => 'success', 'save_type' => $save_type));
}
/**
* @Route("/deletebasketitem/{id}", name="deletebasketitem")
*/
public function deletebasketitem($id): Response
{
$em = $this->getDoctrine()->getManager();
$basketitem = $em->getRepository(Basketitem::class)->find($id);
$the_basket = $basketitem->getBasket();
$em->remove($basketitem);
$em->flush();
if (count($the_basket->getBasketitems()) == 0) {
$em->remove($the_basket);
$em->flush();
}
return $this->redirectToRoute('Handlekurv');
}
/**
* @Route("/emptybasket", name="emptybasket")
*/
public function emptybasket(): Response
{
$basket = $this->getCurrentBasket();
$em = $this->getDoctrine()->getManager();
foreach ($basket->getBasketitems() as $basketitem) {
$em->remove($basketitem);
$em->flush();
}
$em->remove($basket);
$em->flush();
return $this->redirectToRoute('Handlekurv');
}
/**
* @Route("/orderbasket", name="orderbasket")
*/
public function orderbasket(): Response
{
$now = date('Y-m-d H:i:s');
$em = $this->getDoctrine()->getManager();
$basket = $this->getCurrentBasket();
$basket->setCsrftoken('');
$basket->setIsOrder(true);
$basket->setOrdertime(new \Datetime($now));
$em->persist($basket);
$em->flush();
return $this->redirectToRoute('Handlekurv');
}
/**
* @Route("/updateBasketAfterAmountChange",name="updateBasketAfterAmountChange")
*/
public function updateBasketAfterAmountChange(): Response
{
$p = $_POST;
#pre($p,1);
$em = $this->getDoctrine()->getManager();
foreach ($p['amount_selector'] as $basketitem => $amount) {
$basketitem = $em->getRepository(Basketitem::class)->find($basketitem);
$price = $this->getChilidocumentPrice($basketitem->getChilidocument()->getId(),$amount);
$basketitem->setAmount($amount);
$basketitem->setPrice($price);
$em->persist($basketitem);
$em->flush();
}
return new JsonResponse(array('status' => 'success'));
}
/**
* @Route("/getProductPricing/{producttype}/{productid}/{amount}/{basketrowid}", name="getProductPricing")
*/
public function getProductPricing($producttype,$productid,$amount,$basketrowid): Response
{
switch ($producttype) {
case 'chili':
$product = $this->getDoctrine()->getRepository(Chilidocument::class)->find($productid);
$product_price = $product->getPrice();
#dd($product_price);
while ($product_price === null) {
$product = $this->getDoctrine()->getRepository(Chilidocument::class)->findOneBy(['path' => $product->getMother()]);
$product_price = $product->getPrice();
}
break;
}
$pricetype = $product_price->getType();
switch ($pricetype) {
case 'levels':
$output = $this->render('theme_' . config_theme . '/product_pricing_levels.html.twig', [
'id' => $productid,
'basketrowid' => $basketrowid,
'price_amount' => json_decode($product_price->getPriceAmount(),1),
'minimum' => $product_price->getMinimum(),
'maximum' => $product_price->getMaximum(),
'step' => $product_price->getStep(),
'default_amount' => $product_price->getDefaultAmount(),
'amount' => $amount
]);
break;
case 'arbitrary':
$output = $this->render('theme_' . config_theme . '/product_pricing_arbitrary.html.twig', [
'id' => $productid,
'basketrowid' => $basketrowid,
'price_amount' => json_decode($product_price->getPriceAmount(),1),
'minimum' => $product_price->getMinimum(),
'maximum' => $product_price->getMaximum(),
'step' => $product_price->getStep(),
'default_amount' => $product_price->getDefaultAmount(),
'amount' => $amount
]);
break;
}
return $output;
}
/**
* @Route("/activatediscountcode/{code}", name="activatediscountcode")
*/
public function activatediscountcode($code): Response
{
$em = $this->getDoctrine()->getManager();
$current_basket = $this->getCurrentBasket();
if ($code == 'NULL') {
$current_basket->setDiscountcode(NULL);
} else {
$now = date('Y-m-d H:i:s');
$conn = $em->getConnection();
$sql = 'select id from discountcode where code = "' . $code . '" and (user_id = ' . $this->getUser()->getId() . ' or user_id is null) and (valid_from <= "' . $now . '" or valid_from is null) and (valid_to >= "' . $now . '" or valid_to is null)';
$sta = $conn->prepare($sql);
$execute = $sta->executeQuery();
$discount_code_id = $execute->fetchAllAssociative();
if (!$discount_code_id) {
return new JsonResponse(array('status' => 'error'));
}
$discount_code_id = $discount_code_id[0]['id'];
$discount_code = $em->getRepository(Discountcode::class)->find($discount_code_id);
$current_basket->setDiscountcode($discount_code);
}
$em->persist($current_basket);
$em->flush();
return new JsonResponse(array('status' => 'success'));
}
/**
* @Route("/betalmed/{type}", name="betalmedpage")
*/
public function betalmed($type): Response
{
switch ($type) {
case 'vipps':
return $this->redirectToRoute('vipps_pay', [
'basket_token' => $this->getCurrentBasket()->getCsrftoken(),
]);
break;
case 'klarna':
return $this->redirectToRoute('klarnapay', [
'basket_token' => $this->getCurrentBasket()->getCsrftoken(),
]);
break;
case 'stripe':
return $this->redirectToRoute('stripepay', [
'basket_token' => $this->getCurrentBasket()->getCsrftoken(),
]);
break;
case 'easy':
return $this->redirectToRoute('easycheckout', [
'basket_token' => $this->getCurrentBasket()->getCsrftoken(),
]);
break;
}
dd($type);
}
/**
* @Route("/updateBasketAfterDelivery",name="updateBasketAfterDelivery")
*/
public function updateBasketAfterDelivery(Request $request): Response
{
if ($request->getMethod() == 'POST') {
$p = $_POST;
#pre($p,1);
$basket = $this->getDoctrine()->getRepository(Basket::class)->find($p['basket']);
$delivery = $this->getDoctrine()->getRepository(Delivery::class)->find($p['delivery']);
$basket->setDelivery($delivery);
$this->getDoctrine()->getManager()->persist($basket);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse(array('status' => 'success'));
} else {
return new JsonResponse(array('status' => 'error', 'message' => 'No POST!'));
}
}
/**
* @Route("/savebasketmessage",name="savebasketmessage")
*/
public function savebasketmessage(): Response
{
$p = $_POST;
$basket = $this->getCurrentBasket();
$em = $this->getDoctrine()->getManager();
$basket->setMessage($p['message']);
$em->persist($basket);
$em->flush();
return new JsonResponse(array('status' => 'success'));
}
}