<?php
namespace App\Controller;
use App\Entity\Attribute;
use App\Entity\AttributeValue;
use App\Entity\AttributeValueLang;
use App\Entity\Image;
use App\Entity\PSA;
use App\Repository\AttributeLangRepository;
use App\Repository\AttributeRepository;
use App\Repository\AttributeValueLangRepository;
use App\Repository\AttributeValueRepository;
use App\Repository\ImageRepository;
use App\Repository\LangRepository;
use App\Repository\ProductAttributeRepository;
use App\Repository\ERPCommercialDataRepository;
use App\Repository\ERPCommercialDataLangRepository;
use App\Repository\ERPLogisticDataRepository;
use App\Repository\PSARepository;
use App\Repository\SiteRepository;
use App\Services\WebserviceUtils;
use Doctrine\ORM\EntityManagerInterface;
use PrestaShopWebservice;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
#[Route('/attribute/{id}', name: 'app_attribute_value')]
#[IsGranted('ROLE_CONTENT_MANAGER')]
class AttributeValueController extends AbstractController
{
public function __construct(Security $security, TranslatorInterface $translator)
{
$this->twigData = [];
$this->translator = $translator;
$this->security = $security;
$this->twigData = [
'user' => $security->getUser(),
];
}
#[Route('/value', name: '_index')]
public function index(Attribute $attribute, AttributeLangRepository $attributeLangRepository, LangRepository $langRepository, AttributeValueRepository $attributeValueRepository): Response
{
$this->breadcrumb[0]['name'] = $this->translator->trans('page.catalog.Catalog');
$this->breadcrumb[0]['link'] = $this->generateUrl('app_catalog_index');
$this->breadcrumb[0]['last'] = false;
$this->breadcrumb[1]['name'] = $this->translator->trans('page.attribute.Attributes');
$this->breadcrumb[1]['link'] = $this->generateUrl('app_attribute_index');
$this->breadcrumb[1]['last'] = false;
// Get the attribute name depending of the user's langs
$attributeName = "";
$user = $this->security->getUser();
$userInterfaceLang = $user->getInterfaceLang();
$attributLang = $attributeLangRepository->findOneBy(["attribute" => $attribute,'lang'=> $userInterfaceLang]);
if($attributLang != false){
$attributeName = $attributLang->getName();
}
$this->breadcrumb[2]['name'] = $attributeName;
$this->breadcrumb[2]['last'] = true;
$this->twigData['breadcrumb'] = $this->breadcrumb;
$langs = $langRepository->findAll();
$this->twigData['langs'] = $langs;
$this->twigData['attributeValues'] = $attributeValueRepository->findBy(['attribute'=>$attribute->getId()]);
$this->twigData['attributeName'] = $attributeName;
$this->twigData['attribute'] = $attribute;
return $this->render('attribute_value/index.html.twig', $this->twigData);
}
#[Route('/value/new', name: '_new', methods: ['GET', 'POST'])]
public function new(Attribute $attribute, LangRepository $langRepository, AttributeValueRepository $attributeValueRepository, AttributeValueLangRepository $attributeValueLangRepository, Request $request, EntityManagerInterface $entityManager, SluggerInterface $slugger, ImageRepository $imageRepository): Response
{
$this->breadcrumb[0]['name'] = $this->translator->trans('page.catalog.Catalog');
$this->breadcrumb[0]['link'] = $this->generateUrl('app_catalog_index');
$this->breadcrumb[0]['last'] = false;
$this->breadcrumb[1]['name'] = $this->translator->trans('page.attribute.Attributes');
$this->breadcrumb[1]['link'] = $this->generateUrl('app_attribute_index');
$this->breadcrumb[1]['last'] = false;
// Get the attribute name depending of the user's langs
$attributeName = "";
$user = $this->security->getUser();
$userLangs = $user->getLang();
$attributeLangs = $attribute->getAttributeLang();
foreach ($attributeLangs as $key => $attributeLang) {
if($userLangs->contains($attributeLang->getLang())){
$attributeName = $attributeLang;
}
}
// Fallback if the attribute do not have value for the user's lang, get the name of the first lang
if($attributeName == ""){
$attributeName = $attributeLangs[0];
}
$this->breadcrumb[2]['name'] = $attributeName;
$this->breadcrumb[2]['link'] = $this->generateUrl('app_attribute_value_index',['id'=> $attribute->getId()]);
$this->breadcrumb[2]['last'] = false;
$this->breadcrumb[3]['name'] = $this->translator->trans('page.attributeValue.new');;
$this->breadcrumb[3]['last'] = true;
$this->twigData['breadcrumb'] = $this->breadcrumb;
$this->twigData['attribute'] = $attribute;
$langs = $langRepository->findAll();
$this->twigData['langs'] = $langs;
$submit = $request->get("submit");
if($submit == 1){
$attributeValue = new AttributeValue();
$attributeValue->setAttribute($attribute);
$position = $attributeValueRepository->getLastPosition();
$position += 1;
$attributeValue->setPosition($position);
$file = $request->files->get('attribute_texture');
if ($file) {
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$file->guessExtension();
// $attributeTextureImage = $attributeValue->getTexture();
// if ($attributeTextureImage != null) {
// $pathToFile = $this->getParameter('attributeTexture_image_directory').'/'.$attributeTextureImage->getName();
// if (file_exists($pathToFile)) {
// unlink($pathToFile);
// }
// }
// Move the file to the directory where attributeTexture image are stored
try {
$file->move(
$this->getParameter('attributeTexture_image_directory'),
$newFilename
);
$texture = new Image();
$texture->setName($newFilename);
$texture->setDescription('');
$texture->setCover(0);
$imageRepository->add($texture);
$attributeValue->setTexture($texture);
} catch (FileException $e) {
}
}
$attributeValueRepository->add($attributeValue);
$attributeFormData = $request->get("attributeValue");
$attributeValueLang = $attributeFormData['value'];
foreach ($attributeValueLang as $lang_id => $item) {
$attributeValueLang = new AttributeValueLang();
$lang = $langRepository->find($lang_id);
$attributeValueLang->setLang($lang);
$attributeValueLang->setAttributeValue($attributeValue);
$attributeValueLang->setValue($item);
$attributeValueLangRepository->add($attributeValueLang);
}
$entityManager->flush();
return $this->redirectToRoute('app_attribute_value_index', ['id'=>$attribute->getId()], Response::HTTP_SEE_OTHER);
}
return $this->render('attribute_value/new.html.twig', $this->twigData);
}
#[Route('/value/{id_value}/edit', name: '_edit', methods: ['GET', 'POST'])]
public function edit(Attribute $attribute, $id_value, LangRepository $langRepository, AttributeValueRepository $attributeValueRepository, AttributeValueLangRepository $attributeValueLangRepository, Request $request, EntityManagerInterface $entityManager, SluggerInterface $slugger, ImageRepository $imageRepository): Response
{
$this->breadcrumb[0]['name'] = $this->translator->trans('page.catalog.Catalog');
$this->breadcrumb[0]['link'] = $this->generateUrl('app_catalog_index');
$this->breadcrumb[0]['last'] = false;
$this->breadcrumb[1]['name'] = $this->translator->trans('page.attribute.Attributes');
$this->breadcrumb[1]['link'] = $this->generateUrl('app_attribute_index');
$this->breadcrumb[1]['last'] = false;
// Get the attribute name depending of the user's langs
$attributeName = "";
$user = $this->security->getUser();
$userLangs = $user->getLang();
$attributeLangs = $attribute->getAttributeLang();
foreach ($attributeLangs as $key => $attributeLang) {
if($userLangs->contains($attributeLang->getLang())){
$attributeName = $attributeLang;
}
}
// Fallback if the attribute do not have value for the user's lang, get the name of the first lang
if($attributeName == ""){
$attributeName = $attributeLangs[0];
}
$this->breadcrumb[2]['name'] = $attributeName;
$this->breadcrumb[2]['link'] = $this->generateUrl('app_attribute_value_index',['id'=> $attribute->getId()]);
$this->breadcrumb[2]['last'] = false;
$this->breadcrumb[3]['name'] = $this->translator->trans('page.attributeValue.edit');
$this->breadcrumb[3]['last'] = true;
$this->twigData['breadcrumb'] = $this->breadcrumb;
$this->twigData['attribute'] = $attribute;
$langs = $langRepository->findAll();
$this->twigData['langs'] = $langs;
$attributeValue = $attributeValueRepository->find($id_value);
$this->twigData['attributeValue'] = $attributeValue;
$submit = $request->get("submit");
if($submit == 1){
$attributeFormData = $request->get("attributeValue");
if (isset($attributeFormData['isColor'])) {
$file = $request->files->get('attribute_texture');
if ($file) {
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$file->guessExtension();
$attributeTextureImage = $attributeValue->getTexture();
if ($attributeTextureImage != null) {
$pathToFile = $this->getParameter('attributeTexture_image_directory').'/'.$attributeTextureImage->getName();
if (file_exists($pathToFile)) {
unlink($pathToFile);
}
}
// Move the file to the directory where attributeTexture image are stored
try {
$file->move(
$this->getParameter('attributeTexture_image_directory'),
$newFilename
);
$texture = new Image();
$texture->setName($newFilename);
$texture->setDescription('');
$texture->setCover(0);
$imageRepository->add($texture);
$attributeValue->setTexture($texture);
} catch (FileException $e) {
dd($e);
}
}
}else{
$attributeTextureImage = $attributeValue->getTexture();
if ($attributeTextureImage != null) {
$pathToFile = $this->getParameter('attributeTexture_image_directory').'/'.$attributeTextureImage->getName();
if (file_exists($pathToFile)) {
unlink($pathToFile);
}
$attributeValue->setTexture(null);
}
}
$attributeValueLang = $attributeFormData['value'];
foreach ($attributeValueLang as $lang_id => $item) {
$attributeValueLang = $attributeValueLangRepository->findOneBy(['lang'=>$lang_id,'attributeValue'=>$attributeValue->getId()]);
if($attributeValueLang == null){
$attributeValueLang = new AttributeValueLang();
$lang = $langRepository->find($lang_id);
$attributeValueLang->setLang($lang);
$attributeValueLang->setAttributeValue($attributeValue);
}
$attributeValueLang->setValue($item);
$attributeValueLangRepository->add($attributeValueLang);
}
if(isset($attributeFormData['isColor'])){
$attributeValue->setColor($attributeFormData['color']);
}else{
$attributeValue->setColor(null);
}
$attributeValueRepository->add($attributeValue);
$entityManager->flush();
return $this->redirectToRoute('app_attribute_value_index', ['id'=>$attribute->getId()], Response::HTTP_SEE_OTHER);
}
return $this->render('attribute_value/edit.html.twig', $this->twigData);
}
#[Route('/value/{id_value}', name: '_delete', methods: ['POST'])]
public function delete(Attribute $attribute, $id_value, AttributeValueRepository $attributeValueRepository, ProductAttributeRepository $productAttributeRepository, AttributeValueLangRepository $attributeValueLangRepository, Request $request, ERPCommercialDataLangRepository $ERPCommercialDataLangRepository, ERPCommercialDataRepository $ERPCommercialDataRepository, ERPLogisticDataRepository $ERPLogisticDataRepository): Response
{
$attributeValue = $attributeValueRepository->find($id_value);
$attribute = $attributeValue->getAttribute();
if ($this->isCsrfTokenValid('delete'.$id_value, $request->request->get('_token'))) {
$attributeValueLang = $attributeValueLangRepository->findBy(['attributeValue' => $id_value]);
foreach ($attributeValueLang as $key => $item) {
$attributeValueLangRepository->remove($item);
}
$productAttributes = $attributeValue->getProductAttributes();
foreach ($productAttributes as $key => $productAttribute) {
$ERPCommercialDataLangs = $ERPCommercialDataLangRepository->findBy(['productAttribute' => $productAttribute]);
if ($ERPCommercialDataLangs != null) {
foreach ($ERPCommercialDataLangs as $ERPCommercialDataLang) {
$ERPCommercialDataLang = $ERPCommercialDataLangRepository->find($ERPCommercialDataLang->getId());
// dd($ERPCommercialDataLang);
if ($ERPCommercialDataLang != null) {
$ERPCommercialDataLang->setProductAttribute(null);
$ERPCommercialDataLang->setProduct(null);
$ERPCommercialDataLang->setERPCommercialData(null);
$ERPCommercialDataLangRepository->remove($ERPCommercialDataLang, true);
}
}
}
$ERPCommercialData = $ERPCommercialDataRepository->findOneBy(['productAttribute' => $productAttribute]);
if ($ERPCommercialData != null) {
$ERPCommercialData->setProductAttribute(null);
$ERPCommercialData->setProduct(null);
$ERPCommercialDataRepository->remove($ERPCommercialData, true);
}
if ($productAttribute->getERPLogisticData() != null) {
$productAttribute->getERPLogisticData()->setProductAttribute(null);
$productAttribute->getERPLogisticData()->setProduct(null);
$ERPLogisticDataRepository->remove($productAttribute->getERPLogisticData(), true);
}
$productAttributeRepository->remove($productAttribute, true);
}
$attributeValueRepository->remove($attributeValue, true);
}
return $this->redirectToRoute('app_attribute_value_index', ['id'=>$attribute->getId()], Response::HTTP_SEE_OTHER);
}
#[Route('/sync/{id_value}', name: '_sync', methods: ['GET'])]
public function sync(Attribute $attribute, $id_value, AttributeLangRepository $attributeLangRepository, AttributeValueRepository $attributeValueRepository,AttributeValueLangRepository $attributeValueLangRepository, LangRepository $langRepository, Request $request, SiteRepository $siteRepository, PSARepository $PSARepository): Response
{
$debug = false;
$sites = $siteRepository->findAll();
$attributeValue = $attributeValueRepository->find($id_value);
$errors = [];
foreach ($sites as $key => $site) {
$attributeLangs = $attribute->getAttributeLang();
$attributeLang = null;
foreach ($attributeLangs as $keyAttributeLang => $attributeLang) {
if ($attributeLang->getLang() == $this->security->getUser()->getInterfaceLang()) {
$attributeLang = $attributeLang;
break;
}
}
$PSAAttribute = $PSARepository->findOneBy(['entityName' => "attribute", 'entityId' => $attribute->getId(), 'siteId' => $site->getId()]);
if($PSAAttribute == null){
$error = $this->translator->trans('page.attributeValue.error.AttributeValueNotSync', ['%attribute%' => $attributeLang->getName()]);
if(in_array($error, $errors) == false){
$errors[] = $error;
}
}
}
if(!empty($errors)){
foreach ($errors as $keyError => $error) {
$this->addFlash('error', ['from'=>$this->translator->trans('page.product.Sync'),'message'=> $error]);
}
return $this->redirectToRoute('app_attribute_value_index', ['id'=>$attribute->getId()], Response::HTTP_SEE_OTHER);
die;
}
foreach ($sites as $key => $site) {
$url = $site->getUrl();
$key = $site->getApiKey();
$webService = new PrestaShopWebservice($url, $key, $debug);
$webServiceUtils = new WebserviceUtils($webService, $url);
$langs = $webServiceUtils->getSiteLangs();
$psaAttributeValue = $PSARepository->findOneBy(['entityId'=> $attributeValue->getId(), "entityName"=>'attributeValue', "siteId"=>$site->getId()]);
$attributeValueColors = $attributeValueRepository->findWithColor($attributeValue);
$attributeIsColor = false;
$psaParentAttribute = $PSARepository->findOneBy(['entityId'=> $attribute->getId(), "entityName"=>'attribute', "siteId"=>$site->getId()]);
$attributeXML = $webService->get(['resource' => 'product_options', 'id'=>$psaParentAttribute->getInSiteId()]);
$attributeValueXML = $attributeXML->product_option[0]->associations->product_option_values->product_option_value;
$attributeValuePosition = count($attributeValueXML);
if(count($attributeValueColors) > 0){
$attributeIsColor = true;
}
if($psaAttributeValue != null){
try {
$psaParentAttribute = $PSARepository->findOneBy(['entityId'=> $attribute->getId(), "entityName"=>'attribute', "siteId"=>$site->getId()]);
$xmlResponse = $webService->get(['resource' => 'product_option_values', 'id'=>$psaAttributeValue->getInSiteId()]);
$productFeatureXML = $xmlResponse->product_option_value[0];
$productFeatureXML->id_attribute_group = $psaParentAttribute->getInSiteId();
if($attributeValue->getColor() != null){
$productFeatureXML->color = $attributeValue->getColor();
}
foreach ($langs as $keyLang => $lang) {
if ($lang['icu'] == "en") {
$lang['icu'] = "gb";
}
$langPimdam = $langRepository->findOneBy(['ICU'=>$lang['icu']]);
$attributeValueLang = $attributeValueLangRepository->findOneBy(['lang'=> $langPimdam, 'attributeValue'=>$attributeValue->getId()]);
$productFeatureXML->name->language[$keyLang] = $attributeValueLang->getValue();
}
$opt = ['resource' => 'product_option_values'];
$opt['putXml'] = $xmlResponse->asXML();
$opt['id'] = (int) $productFeatureXML->id;
$return = $webService->edit($opt);
} catch (\Throwable $th) {
$PSARepository->Remove($psaAttributeValue, true);
return $this->redirectToRoute('app_attribute_value_sync', ['id'=>$attributeValue->getAttribute()->getId(), 'id_value'=>$id_value], Response::HTTP_SEE_OTHER);
}
}else{
$psaParentAttribute = $PSARepository->findOneBy(['entityId'=> $attribute->getId(), "entityName"=>'attribute', "siteId"=>$site->getId()]);
$xmlResponse = $webService->get(['url' => $url . '/api/product_option_values?schema=blank']);
$productFeatureXML = $xmlResponse->product_option_value[0];
$productFeatureXML->position = $attributeValuePosition;
$productFeatureXML->id_attribute_group = $psaParentAttribute->getInSiteId();
if($attributeValue->getColor() != null){
$productFeatureXML->color = $attributeValue->getColor();
}
foreach ($langs as $keyLang => $lang) {
if ($lang['icu'] == "en") {
$lang['icu'] = "gb";
}
$langPimdam = $langRepository->findOneBy(['ICU'=>$lang['icu']]);
$attributeValueLang = $attributeValueLangRepository->findOneBy(['lang'=> $langPimdam, 'attributeValue'=>$attributeValue->getId()]);
$productFeatureXML->name->language[$keyLang] = $attributeValueLang->getValue();
}
$opt = ['resource' => 'product_option_values'];
$opt['postXml'] = $xmlResponse->asXML();
$return = $webService->add($opt);
$returnedId = intval($return->product_option_value[0]->id);
$psaAttributeValue = new PSA();
$psaAttributeValue->setEntityId($attributeValue->getId());
$psaAttributeValue->setEntityName('attributeValue');
$psaAttributeValue->setInSiteId($returnedId);
$psaAttributeValue->setSiteId($site->getId());
$PSARepository->add($psaAttributeValue, true);
}
}
return $this->redirectToRoute('app_attribute_value_index', ['id'=>$attribute->getId()], Response::HTTP_SEE_OTHER);
}
}