src/GlobalBundle/Controller/DefaultController.php line 45

Open in your IDE?
  1. <?php
  2. namespace GlobalBundle\Controller;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use Pimcore\Model\DataObject;
  7. use Pimcore\Model\DataObject\Product;
  8. use Pimcore\Model\DataObject\Compliance;
  9. use Pimcore\Model\DataObject\Port;
  10. use Symfony\Component\Security\Core\User\UserInterface;
  11. use GlobalBundle\Controller\BaseController;
  12. use Pimcore\Model\DataObject\BookADemo;
  13. use Pimcore\Model\DataObject\MiSourceContact;
  14. use GlobalBundle\AppHelpers\GeneralHelper;
  15. use Pimcore\Model\DataObject\Category;
  16. use Pimcore\Model\DataObject\Customer;
  17. use Pimcore\Model\DataObject\MarketingReport;
  18. use Pimcore\Model\DataObject\MarketingReportResponses;
  19. use Pimcore\Model\DataObject\SupplierCompany;
  20. use Pimcore\Placeholder\DataObject as PlaceholderDataObject;
  21. use App\Templating\ViewModel;
  22. use GlobalBundle\Form\LoginFormType;
  23. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  24. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  25. use CustomerManagementFrameworkBundle\Security\OAuth\Exception\AccountNotLinkedException;
  26. use GlobalBundle\Services\CatalogServices;
  27. use Pimcore\Model\DataObject\SalesCampaign;
  28. use Pimcore\Model\DataObject\SalesCampaignVisitors;
  29. use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
  30. use GlobalBundle\Services\ProductServices;
  31. use Pimcore\Model\DataObject\Wishlist;
  32. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  33. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  34. use Pimcore\Model\Asset;
  35. use Pimcore\Model\DataObject\Country;
  36. use Pimcore\Model\DataObject\Service;
  37. use Pimcore\Model\Element\Note;
  38. use App\Paginator\Paginator;
  39. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  40. use Pimcore\File;
  41. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  42. use Symfony\Component\HttpFoundation\JsonResponse;
  43. class DefaultController extends BaseController
  44. {
  45.     /**
  46.      * Description:- Load Default View
  47.     */
  48.     public function defaultFooterAction(Request $request){
  49.     }
  50.     /**
  51.      * @Route("/global")
  52.      */
  53.     public function indexAction(Request $request)
  54.     {
  55.         return new Response('Hello world from global');
  56.     }
  57.     /**
  58.      * @Route("/getDescription")
  59.      */
  60.     public function getDescription(Request $request)
  61.     {
  62.         $myObject = DataObject\Product::getById($request->get('id'));
  63.         if (!empty($request->get('presetId'))) {
  64.             $productData = DataObject\DescriptionPreset::getById($request->get('presetId'));
  65.             $presetDescription = $productData->getDescription('en');
  66.         }
  67.         return $this->json($presetDescription);
  68.     }
  69.      /**
  70.      * Description: Misource page not found
  71.      * @Route("/page-not-found", name="page-not-found")
  72.      */
  73.     public function pageNotFoundAction(Request $request, UserInterface $user = null)
  74.     {
  75.         $viewModel = new ViewModel();
  76.         $homePageURL = \Pimcore\Tool::getHostUrl();
  77.         if(!$this->editmode) {
  78.             if ($user && $this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  79.                 $homePageURL = $homePageURL.'/home';
  80.             }
  81.         }
  82.         $viewModel->homePageUrl = $homePageURL;
  83.         return $viewModel->getAllParameters();
  84.     }
  85.     /**
  86.      * Description: Misource landing page
  87.      * @Route("/",name="landing");
  88.      */
  89.     public function defaultAction(Request $request, UserInterface $user = null, AuthenticationUtils $authenticationUtils, SessionInterface $session)
  90.     {
  91.         if(!$this->editmode) {
  92.             if ($user && $this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  93.                 return $this->redirectToRoute('home');
  94.             }
  95.         }
  96.         $categoriesListing = new Category\Listing();
  97.         $catagories = $categoriesListing->load();
  98.         $firstLavelCatagory = [];
  99.         foreach($catagories as $category){
  100.             if($category->getParent()->getType()=='folder'){
  101.                 array_push($firstLavelCatagory,$category);
  102.             }
  103.         }
  104.         $countryListing = new Country\Listing();
  105.         $countryListing->setOrderKey("o_key");
  106.         $countryListing->setOrder("ASC");
  107.         $countries = $countryListing->load();
  108.         
  109.         $object = new SupplierCompany();
  110.         $markets = $object->getClass()->getFieldDefinition("markets");
  111.         $marketOptions = $markets->getOptions();
  112.         $companyType = $object->getClass()->getFieldDefinition("companyType");
  113.         $companyTypeOptions = $companyType->getOptions();
  114.         $complianceListing = new Compliance\Listing();
  115.         $complianceListing->load();
  116.         $portListing = new Port\Listing();
  117.         $portListing->load();
  118.         $salesCampaignListing = new SalesCampaign\Listing();
  119.         $salesCampaignListing->setCondition("isActive = ?", 1);
  120.         $salesCampaignListing->setCondition("isVisible = ?", 1);
  121.         // $salesCampaignListing->setOrderKey("o_creationDate");
  122.         // $salesCampaignListing->setOrder("desc");
  123.         $salesCampaignListing->setOrderKey("sequenceNumber");
  124.         $salesCampaignListing->setOrder("ASC");
  125.         $salesCampaignListing->setUnpublished(false);
  126.         $salesCampaignListing->load();
  127.         // get the login error if there is one
  128.         $url_components = parse_url($request->getUri());
  129.         parse_str($url_components['query'] ?? '', $params);
  130.         $error = $authenticationUtils->getLastAuthenticationError();
  131.         // to load the token to prepopulate the registration form with account data.
  132.         if ($error instanceof AccountNotLinkedException) {
  133.             // this can be anything - for simplicity we just use an UUID as it is unique and random
  134.             $registrationKey = (string) Uuid::uuid4();
  135.           //  $oAuthHandler->saveToken($registrationKey, $error->getToken());
  136.             return $this->redirectToRoute('account-register', [
  137.                 'registrationKey' => $registrationKey
  138.             ]);
  139.         }
  140.         // last username entered by the user
  141.         $lastUsername = $authenticationUtils->getLastUsername();
  142.         $formData = [
  143.             '_username' => $lastUsername
  144.         ];
  145.         $form = $this->createForm(LoginFormType::class, $formData, [
  146.             'action' => $this->generateUrl('account-login'),
  147.         ]);
  148.         return [
  149.                 'CDN_URL' => PIMCORE_CDN_BASEURL,
  150.                 'categories'=>$firstLavelCatagory,
  151.                 'countries'=>$countries,
  152.                 'compliances' => $complianceListing,
  153.                 'ports' => $portListing,
  154.                 'marketOptions' => $marketOptions,
  155.                 'companyTypeOptions' => $companyTypeOptions,
  156.                 'form' => $form->createView(),
  157.                 'error' => $error,
  158.                 'dClass' => '',
  159.                 'editmode'=>$this->editmode,
  160.                 'salesCampaign' => $salesCampaignListing,
  161.                 'errorFlag'=>$params['errorFlag'] ?? '',
  162.                 'errorType'=>$params['errorType'] ?? '',
  163.             ];
  164.     }
  165.     /**
  166.      * Description: Misource landing page
  167.      */
  168.     public function defaultOldAction(Request $request, UserInterface $user = null, AuthenticationUtils $authenticationUtils, SessionInterface $session)
  169.     {
  170.         if(!$this->editmode) {
  171.             if ($user && $this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  172.                 return $this->redirectToRoute('home');
  173.             }
  174.         }
  175.         $categoriesListing = new Category\Listing();
  176.         $catagories = $categoriesListing->load();
  177.         $firstLavelCatagory = [];
  178.         foreach($catagories as $category){
  179.             if($category->getParent()->getType()=='folder'){
  180.                 array_push($firstLavelCatagory,$category);
  181.             }
  182.         }
  183.         $object = new SupplierCompany();
  184.         $markets = $object->getClass()->getFieldDefinition("markets");
  185.         $marketOptions = $markets->getOptions();
  186.         $companyType = $object->getClass()->getFieldDefinition("companyType");
  187.         $companyTypeOptions = $companyType->getOptions();
  188.         $complianceListing = new Compliance\Listing();
  189.         $complianceListing->load();
  190.         $portListing = new Port\Listing();
  191.         $portListing->load();
  192.         // get the login error if there is one
  193.         $error = $authenticationUtils->getLastAuthenticationError();
  194.         // to load the token to prepopulate the registration form with account data.
  195.         if ($error instanceof AccountNotLinkedException) {
  196.             // this can be anything - for simplicity we just use an UUID as it is unique and random
  197.             $registrationKey = (string) Uuid::uuid4();
  198.           //  $oAuthHandler->saveToken($registrationKey, $error->getToken());
  199.             return $this->redirectToRoute('account-register', [
  200.                 'registrationKey' => $registrationKey
  201.             ]);
  202.         }
  203.         // last username entered by the user
  204.         $lastUsername = $authenticationUtils->getLastUsername();
  205.         $formData = [
  206.             '_username' => $lastUsername
  207.         ];
  208.         $form = $this->createForm(LoginFormType::class, $formData, [
  209.             'action' => $this->generateUrl('account-login'),
  210.         ]);
  211.         return [
  212.                 'categories'=>$firstLavelCatagory,
  213.                 'compliances' => $complianceListing,
  214.                 'ports' => $portListing,
  215.                 'marketOptions' => $marketOptions,
  216.                 'companyTypeOptions' => $companyTypeOptions,
  217.                 'form' => $form->createView(),
  218.                 'error' => $error,
  219.                 'dClass' => 'display:none;'
  220.             ];
  221.     }
  222.     /**
  223.      *  Description:- Misource landing page - Book A demo ajax submit action
  224.      *
  225.      * @Route("/booking",name="bookAdemo");
  226.      * @param Request $request
  227.      * @return success or error msg
  228.     */
  229.     public function bookingAction(Request $request){
  230.         if($request->getMethod() === "POST") {
  231.            if($request->get("submitAction") == 'bookAdemo') {
  232.                $firstName = $request->get("firstName");
  233.                $lastName = $request->get("lastName");
  234.                $jobRole = $request->get("jobRole");
  235.                $companyType = $request->get("companyType");
  236.                $companySize = $request->get("companySize");
  237.                $companyName = $request->get("companyName");
  238.                $email = $request->get("email");
  239.                $unique_key = "BD-".time();
  240.                $c = new BookADemo();
  241.                $c->setFirstName($firstName);
  242.                $c->setLastName($lastName);
  243.                $c->setJobRole($jobRole);
  244.                $c->setCompanyType($companyType);
  245.                $c->setCompanySize($companySize);
  246.                $c->setCompanyName($companyName);
  247.                $c->setEmail($email);
  248.                $c->setParent(GeneralHelper::validateFolderPath(BOOKADEMO_PATH));
  249.                $c->setKey($unique_key);
  250.                $c->setPublished(true);
  251.                try {
  252.                    $c->save();
  253.                    return new Response('success');
  254.                } catch(\Exception $e) {
  255.                    return new Response('error');
  256.                }
  257.            }
  258.         }
  259.    }
  260.    /**
  261.     *  Description:- Misource landing page - footer contact form ajax submit action
  262.     *
  263.     * @Route("/contact",name="contactUs");
  264.     * @param Request $request
  265.     * @return success or error msg
  266.    */
  267.    public function contactAction(Request $request){
  268.         if($request->getMethod() === "POST") {
  269.             if($request->get("submitAction") == 'contactUs') {
  270.                $message = $request->get("message");
  271.                $name = $request->get("name");
  272.                $email = $request->get("email");
  273.                $inquiryType = $request->get("inquiryType");
  274.                $submitBy = $request->get("submitBy");               
  275.                $unique_key = "CU-".time();
  276.                $cntus = new MiSourceContact();
  277.                $cntus->setName($name);
  278.                $cntus->setEmail($email);
  279.                $cntus->setMessage($message);
  280.                $cntus->setInquiryType($inquiryType);
  281.                $cntus->setSubmitBy($submitBy);
  282.                $cntus->setParent(GeneralHelper::validateFolderPath(CONTACTUS_PATH));
  283.                $cntus->setKey($unique_key);
  284.                $cntus->setPublished(true);
  285.                try {
  286.                    $cntus->save();
  287.                    $websiteConfig = \Pimcore\Config::getWebsiteConfig();
  288.                    $mailReciver = $websiteConfig->get('MailNotification');
  289.                    $contactUs = array('name' => $name, 'email' => $email, 'message' => $message, 'inquiryType' => $inquiryType);
  290.                    GeneralHelper::sendMail($mailReciver,'/'.EMAILDOCUMENT_PATH.'/Emails/ContactUs/contactUs',$contactUs);
  291.                    return new Response('success');
  292.                } catch(\Exception $e) {
  293.                    return new Response('error');
  294.                }
  295.            }
  296.         }
  297.    }
  298.     /**
  299.      * @Route("/product-anonymous-details", name="product-anonymous-details")
  300.      *
  301.      * @param Request $request  
  302.      * @return \Symfony\Component\HttpFoundation\Response
  303.      *
  304.      * @throws \Exception
  305.      */
  306.     public function productDetailAnonymousAction(Request $request)
  307.     {
  308.         try {
  309.             $websiteConfig = \Pimcore\Config::getWebsiteConfig();
  310.             $showAnonymousSalePrice = $websiteConfig->get('SHOW_ANONYMOUS_USER_SALEPRICE');
  311.             $showAnonymousSalePrice = isset($showAnonymousSalePrice) && ($showAnonymousSalePrice == 'true');
  312.             $productServices = new ProductServices();
  313.             $countryListing = new Country\Listing();
  314.             $countryListing->setOrderKey("o_key");
  315.             $countryListing->setOrder("ASC");
  316.             $countries = $countryListing->load();
  317.             $productsVariantData = [];
  318.             $productId = $request->get('productId');
  319.             $product = Product::getById($productId);
  320.             if ($product === null) {
  321.                 throw new \Exception('Product not found');
  322.             }
  323.             // if (!$request->get('pimcore_object_preview')) {
  324.             //     $paramBag['admin_preview'] = true;
  325.             //     $checkAllowed = $productServices->checkAllowedProduct($product);
  326.             // } else {
  327.             //     $checkAllowed = true;
  328.             // }
  329.             // checkProd:
  330.             // if ($product->getType() == 'variant') {
  331.                 
  332.             //     $product = $product->getParent();
  333.             //     goto checkProd;
  334.             // }
  335.             // $variantType = '';
  336.             $variantType = $product->getVariantType();
  337.             $proID = $product->getId();
  338.             $proMaterial = $product->getMaterial();
  339.             $proColor = $product->getColor();
  340.             $proFinish = $product->getFinish();
  341.             if($variantType == 'Dimension'){
  342.                 $prodData = $productServices->getProductChid($product);
  343.                 $productsVariantData['variant'] = $prodData;
  344.             }
  345.             $productsVariantData[$proID] = [];
  346.             $productsVariantData['isCMF'] = false;
  347.             $productsVariantData['variantType'] = $variantType;
  348.             $materialData = GeneralHelper::getMasterData('Material', $proMaterial[0]);
  349.             $productsVariantData[$proID]['material'] = $materialData;
  350.             $colorData = GeneralHelper::getMasterData('color', $proColor[0]);
  351.             $finishData = GeneralHelper::getMasterData('finish', $proFinish[0]);
  352.             $productsVariantData[$proID]['color'] = $colorData;
  353.             $productsVariantData[$proID]['finish'] = $finishData; 
  354.             $form = $this->createForm(LoginFormType::class, $formData, [
  355.                 'action' => $this->generateUrl('account-login'),
  356.             ]);
  357.             $finish = $product->getFinish() ? $this->getProductCMF("Finish", $product->getFinish()) : '';
  358.             return $this->render('@Global/product/anonymous.product.details.html.twig', [
  359.                 'form' => $form->createView(),
  360.                 'countries'=>$countries,
  361.                 'productVariant' => $productsVariantData,
  362.                 'MembershipType' => 'Signature',
  363.                 'editmode'=>$this->editmode ?? "",
  364.                 'status'=>true,
  365.                 'product'=>$product,
  366.                 'showAnonymousSalePrice'=>$showAnonymousSalePrice,
  367.                 'finish'=>$finish,
  368.             ]);
  369.         } catch (\Exception $e) {
  370.             error_log($e->getMessage());
  371.             return $this->render('@Global/error/no_data_found.html.twig', ['message' => 'An error occurred while processing your request.']);
  372.         }
  373.     }
  374.     public function getProductCMF($class, array $fieldData): string
  375.     {
  376.         $result = array_map(function($item) use ($class) {
  377.             $masterData = GeneralHelper::getMasterData($class, $item);
  378.             return $masterData['name'];
  379.         }, $fieldData);
  380.         return implode(', ', $result);
  381.     }
  382.    /**
  383.      * @Route("/salescampaign/{campaignname}~s{campaign}", name="salesCampaign-detail", requirements={"campaignname"="[\w-]+", "campaign"="\d+"})
  384.      *
  385.      * @param Request $request
  386.      * @param HeadTitle $headTitleHelper
  387.      * @param BreadcrumbHelperService $breadcrumbHelperService
  388.      * @param Factory $ecommerceFactory
  389.      * @param SegmentTrackingHelperService $segmentTrackingHelperService
  390.      * @param Concrete $product built-in parameter conversion, please see https://github.com/pimcore/pimcore/pull/5554
  391.      *
  392.      * @return \Symfony\Component\HttpFoundation\Response
  393.      *
  394.      * @throws \Exception
  395.      */
  396.     public function campaignDetailAction(
  397.         Request $request,
  398.         UserInterface $user = null, SessionInterface $session
  399.     ){
  400.         $session->remove('totalProductIds');
  401.         $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;      
  402.         $isAbleToUnpublished = false;  
  403.         $viewModel = new ViewModel();
  404.         if (!empty($customer)) {
  405.             $customerId = $customer->getId();
  406.             $customerObj = Customer::getById($customerId);
  407.             $isAbleToUnpublished = $customerObj->getAbleToUnpublished();            
  408.         }
  409.         $params = array_merge($request->query->all(), $request->attributes->all());
  410.         //$salesCampaignDetails = SalesCampaign::getById($params['campaign'],['o_published' => true]);
  411.         $list = new DataObject\SalesCampaign\Listing();
  412.         $list->setCondition("o_id = ?", [$params['campaign']]);
  413.         $list->addConditionParam("o_published = ?", true, "AND");
  414.         $salesCampaignDetails = $list->load()[0];
  415.         //dd($salesCampaignDetails);
  416.         $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;      
  417.         $isAbleToSequence = false;  
  418.         if (!empty($customer)) {
  419.             $customerId = $customer->getId();
  420.             $customerObj = Customer::getById($customerId);
  421.             $isAbleToSequence = $customerObj->getAbleToSequenceProduct();            
  422.         }
  423.         $salesCampaign = array();
  424.         $salesCampaign['status'] = '';
  425.         $salesCampaign['editmode']=false;
  426.         $salesCampaign['dClass']='';
  427.         
  428.         $countryListing = new Country\Listing();
  429.         $countryListing->setOrderKey("o_key");
  430.         $countryListing->setOrder("ASC");
  431.         $countries = $countryListing->load();
  432.         $formData = [
  433.             '_username' => $lastUsername
  434.         ];
  435.         $form = $this->createForm(LoginFormType::class, $formData, [
  436.             'action' => $this->generateUrl('account-login'),
  437.         ]);
  438.         $salesCampaign['form'] = $form->createView();
  439.         $salesCampaign['isVerified'] = 1;
  440.         if(!$salesCampaignDetails){
  441.           //throw new NotFoundHttpException('SalesCampaign not found.');
  442.           //return $this->redirectToRoute('page-not-found');
  443.           $salesCampaign['status'] = 'notFound';
  444.           return $this->render('@Global/default/salesCampaign.html.twig',$salesCampaign);
  445.         }
  446.         
  447.         $isAccountManager = "";
  448.         $customerObj = "";
  449.         if($customer){
  450.             $customerId = $customer->getId();
  451.             $customerObj = Customer::getById($customerId);
  452.             $isAccountManager=  $customerObj->getIsAccountManager();      
  453.         } 
  454.         if($salesCampaignDetails->getIsActive() != 1 && !$isAccountManager){
  455.           //return $this->redirectToRoute('page-not-found');
  456.           $salesCampaign['status'] = 'notFound';
  457.           return $this->render('@Global/default/salesCampaign.html.twig',$salesCampaign);
  458.         }
  459.         if($salesCampaignDetails->getShareableLink() !== \Pimcore\Tool::getHostUrl() . '/salescampaign/'.$params['campaignname'].'~s'.$params['campaign']){
  460.           //return $this->redirectToRoute('page-not-found');
  461.           $salesCampaign['status'] = 'notFound';
  462.           return $this->render('@Global/default/salesCampaign.html.twig',$salesCampaign);
  463.         }
  464.         $salesCampaign['campaignType'] = $salesCampaignDetails->getCampaignType();
  465.         $salesCampaign['bgcolor'] = substr($salesCampaignDetails->getBackgroundColor(), 0, 7);
  466.         $salesCampaign['bannerimg'] = $salesCampaignDetails->getBannerImage();
  467.         $salesCampaign['bannerimgmobile'] = $salesCampaignDetails->getBannerImageMobile();
  468.         $salesCampaign['isPublic'] = $salesCampaignDetails->getIsPublic();
  469.         $salesCampaign['accessCode'] = $salesCampaignDetails->getAccessCode();
  470.         $salesCampaign['salesCampaignId'] = $salesCampaignDetails->getId();
  471.         if($salesCampaign['campaignType'] == 'Lead' && $salesCampaign['isPublic'] != 1){
  472.           $salesCampaign['isVerified'] = 0;
  473.         }
  474.         if($salesCampaign['campaignType'] == 'Lead' && $salesCampaign['accessCode'] == ''){
  475.             $salesCampaign['noAccessCode'] = 1;
  476.         }else{
  477.             $salesCampaign['noAccessCode'] = 0;
  478.         }
  479.         
  480.         if($request->getMethod() === "POST") {
  481.            if($request->get("submitAction") == 'SCAccessCode') {
  482.               $accessCode = $request->get("SCaccessCode");
  483.               $firstName = $request->get("SCFirstName");
  484.               $lastName = $request->get("SCLastName");
  485.               $email = $request->get("SCemail");
  486.               $phone = $request->get("SCphone");
  487.               $phoneCode = $request->get("SCphoneCode");
  488.               $error=array();
  489.               if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  490.                   $error['email']="*Not Valid";
  491.               }
  492.               if($salesCampaignDetails->getAccessCode() != $accessCode){
  493.                 //$salesCampaign['isVerified'] = 1;
  494.                 $error['accessCode']="*Not Valid";
  495.               }
  496.               if(!empty($error)){
  497.                 return new Response(json_encode(array("status"=>"failed",'code'=>"400","errorData"=>$error)));
  498.               }else{
  499.                 if(!empty($firstName) || !empty($lastName) || !empty($email) || !empty($phone)){
  500.                   $SalesCampaignVisitor = new SalesCampaignVisitors();
  501.                   $SalesCampaignVisitor->setFirstName($firstName);
  502.                   $SalesCampaignVisitor->setLastName($lastName);
  503.                   $SalesCampaignVisitor->setEmail($email);
  504.                   $SalesCampaignVisitor->setPhone($phoneCode.$phone);
  505.                   $SalesCampaignVisitor->setParent(GeneralHelper::validateFolderPath(SALES_CAMPAIGN_VISITORS));
  506.                   $SalesCampaignVisitor->setSalesCampaign($salesCampaignDetails);
  507.                   $SalesCampaignVisitor->setKey($firstName.' '.$lastName.' '.time());
  508.                   $SalesCampaignVisitor->save();
  509.                 }
  510.                 return new Response(json_encode(array("status"=>"success",'code'=>"200")));
  511.               }
  512.            }
  513.         }
  514.         $salesCampaign['title'] = $salesCampaignDetails->getTitle();
  515.         $salesCampaign['subtitle'] = $salesCampaignDetails->getSubTitle();
  516.         $salesCampaign['mainTitle'] = $salesCampaignDetails->getMainTitle();
  517.         $salesCampaign['mainSubTitle'] = $salesCampaignDetails->getMainSubTitle();
  518.         $salesCampaign['shortdesc'] = $salesCampaignDetails->getShortDescription();
  519.         $salesCampaign['desc'] = $salesCampaignDetails->getDescription();
  520.         if (!empty($customer) && $customer->getCustomerType() == 'Supplier') { 
  521.             if($salesCampaignDetails->getProducts()){ 
  522.                 $newcatProduct  =   $salesCampaignDetails->getProducts(); 
  523.                 foreach($newcatProduct as $k1 => $prod){  
  524.                     $customerSupplier   =   $customer->getSupplier();
  525.                     $supplierCompany    =   $customer->getSupplier()->getParent();
  526.                     $supplierCompanyId  =   $supplierCompany->getId();
  527.                     if($prod->getSupplier()->getId() != $supplierCompanyId){  
  528.                         unset($newcatProduct[$k1]);
  529.                     }
  530.                 }
  531.                 $salesCampaign['products'] = $newcatProduct;
  532.             }
  533.         }else{
  534.             $salesCampaign['products'] = $salesCampaignDetails->getProducts();
  535.         }
  536.         $totalProductIds = [];
  537.         foreach ($salesCampaign['products'] as $product) {
  538.                 $totalProductIds[] = $product->getId();
  539.         }
  540.         $session->set('totalProductIds', $totalProductIds);
  541.         $salesCampaign['isAbleToSequence'] = $isAbleToSequence;
  542.         $salesCampaign['isAbleToUnpublished'] = $isAbleToUnpublished;
  543.         $salesCampaign['salesCampaignDetails'] = $salesCampaignDetails;
  544.         $salesCampaign['countries'] =   $countries;
  545.         $salesCampaign['isAccountManager'] =   $isAccountManager;
  546.         $salesCampaign['customerObj'] =   $customerObj;
  547.         $salesCampaign['campaignWishlist'] = $this->getOptionValues("Wishlist");
  548.         //$salesCampaign['companyLists'] = $this->getOptionValues("Company"); 
  549.         if (!empty($customer)) {
  550.             $catalogServices = new CatalogServices();
  551.             $productServices = new ProductServices();
  552.             $catalogServices->getAllUsersByCurrentAccountManagers($viewModel, $customer);
  553.             $salesCampaign['companyLists'] = $viewModel->filterExclusiveSuppliers;
  554.             $salesCampaign['buyerAccountLoginsArr'] = $productServices->getAllBuyerAccounts(false, true);        
  555.         }
  556.         $salesCampaign['embedText'] = $salesCampaignDetails->getEmbedText() ?? "";
  557.         return $this->render('@Global/default/salesCampaign.html.twig',$salesCampaign);
  558.      }
  559.     /**
  560.      * @Route("/marketingreport/{reportname}~mr{report}", name="marketingReport-detail", requirements={"reportname"=".+", "report"="\d+"})
  561.      *
  562.      * @param Request $request
  563.      * @param string $reportname
  564.      * @param int $report
  565.      *
  566.      * @return \Symfony\Component\HttpFoundation\Response
  567.      *
  568.      * @throws \Exception
  569.      */
  570.     public function marketingReportDetailAction(Request $request, string $reportname, int $report, AuthenticationUtils $authenticationUtils, SessionInterface $session)
  571.     {
  572.         if(!$this->editmode) {
  573.             if ($user && $this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  574.                 return $this->redirectToRoute('home');
  575.             }
  576.         }
  577.         $countryListing = new Country\Listing();
  578.         $countryListing->setOrderKey("o_key");
  579.         $countryListing->setOrder("ASC");
  580.         $countries = $countryListing->load();
  581.         // last username entered by the user
  582.         $lastUsername = $authenticationUtils->getLastUsername();
  583.         $formData = [
  584.             '_username' => $lastUsername
  585.         ];
  586.         $form = $this->createForm(LoginFormType::class, $formData, [
  587.             'action' => $this->generateUrl('account-login'),
  588.         ]);
  589.         $reportname = $request->get('reportname');
  590.         $reportId = $request->get('report');
  591.         $reportMarketingObj = MarketingReport::getById($reportId);
  592.         return $this->render('@Global/default/marketingReport.html.twig', [
  593.             'form' => $form->createView(),
  594.             'error' => $error,
  595.             'countries'=>$countries,
  596.             'reportname' => $reportname,
  597.             'report' => $report,
  598.             'editmode'=>$this->editmode,
  599.             'reportMarketingObj' => $reportMarketingObj
  600.         ]);
  601.     }
  602.      /**
  603.      * @Route("/marketingreport/response", name="marketing_report_response", methods={"POST"})
  604.      */
  605.     public function marketingReportResponse(Request $request)
  606.     {
  607.         $formData = $request->request->all();
  608.         $marketingReportId = $formData['marketingReportId'];
  609.         $firstName = $formData['firstName'];
  610.         $lastName = $formData['lastName'];
  611.         $marketingReportObj = MarketingReport::getById($marketingReportId);
  612.         if(!empty($marketingReportObj)){
  613.             $marketingResponses = new MarketingReportResponses();
  614.             foreach ($formData as $key => $value) {
  615.                 $method = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $key)));   
  616.                 if (method_exists($marketingResponses, $method)) {
  617.                     $marketingResponses->$method($value);
  618.                 }
  619.             }
  620.         $marketingResponses->setMarketingReport($marketingReportObj);
  621.         $marketingResponses->setParent(GeneralHelper::validateFolderPath(MARKETING_REPORT_RESPONSES));
  622.         $marketingResponses->setKey($firstName.' '.$lastName.' '.time());
  623.         $marketingResponses->setPublished(true);
  624.         $marketingResponses->save();
  625.         return new Response(json_encode(array("status" => "success", 'code' => "200")));
  626.         }
  627.         return new Response(json_encode(array("status" => "error", 'code' => "404")));
  628.     }
  629.      /**
  630.    * Description: Misource landing page
  631.      * @Route("/overview",name="overview");
  632.      */
  633.   public function overviewAction(Request $request, UserInterface $user = null, AuthenticationUtils $authenticationUtils, SessionInterface $session)
  634.     {
  635.         if(!$this->editmode) {
  636.           if ($user && $this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  637.           return $this->redirectToRoute('home');
  638.           }
  639.         }
  640.         $overviewData = array();
  641.         $categoriesListing = new Category\Listing();
  642.         $catagories = $categoriesListing->load();
  643.         $firstLavelCatagory = [];
  644.         foreach($catagories as $category){
  645.             if($category->getParent()->getType()=='folder'){
  646.                 array_push($firstLavelCatagory,$category);
  647.             }
  648.         }
  649.         $object = new SupplierCompany();
  650.         $markets = $object->getClass()->getFieldDefinition("markets");
  651.         $marketOptions = $markets->getOptions();
  652.         $companyType = $object->getClass()->getFieldDefinition("companyType");
  653.         $companyTypeOptions = $companyType->getOptions();
  654.         $complianceListing = new Compliance\Listing();
  655.         $complianceListing->load();
  656.         $portListing = new Port\Listing();
  657.         $portListing->load();
  658.         $salesCampaignListing = new SalesCampaign\Listing();
  659.         $salesCampaignListing->setCondition("isActive = ?", 1);
  660.         // $salesCampaignListing->setOrderKey("o_creationDate");
  661.         // $salesCampaignListing->setOrder("desc");
  662.         $salesCampaignListing->setOrderKey("sequenceNumber");
  663.         $salesCampaignListing->setOrder("ASC");
  664.         $salesCampaignListing->setUnpublished(false);
  665.         $salesCampaignListing->load();
  666.         // get the login error if there is one
  667.         $error = $authenticationUtils->getLastAuthenticationError();
  668.         // to load the token to prepopulate the registration form with account data.
  669.         if ($error instanceof AccountNotLinkedException) {
  670.             // this can be anything - for simplicity we just use an UUID as it is unique and random
  671.             $registrationKey = (string) Uuid::uuid4();
  672.           //  $oAuthHandler->saveToken($registrationKey, $error->getToken());
  673.             return $this->redirectToRoute('account-register', [
  674.                 'registrationKey' => $registrationKey
  675.             ]);
  676.         }
  677.         // last username entered by the user
  678.         $lastUsername = $authenticationUtils->getLastUsername();
  679.         $formData = [
  680.             '_username' => $lastUsername
  681.         ];
  682.         $form = $this->createForm(LoginFormType::class, $formData, [
  683.             'action' => $this->generateUrl('account-login'),
  684.         ]);
  685.         return [
  686.                 'categories'=>$firstLavelCatagory,
  687.                 'compliances' => $complianceListing,
  688.                 'ports' => $portListing,
  689.                 'marketOptions' => $marketOptions,
  690.                 'companyTypeOptions' => $companyTypeOptions,
  691.                 'form' => $form->createView(),
  692.                 'error' => $error,
  693.                 'dClass' => '',
  694.                 'salesCampaign' => $salesCampaignListing
  695.             ];
  696.     }
  697.     
  698.     /**
  699.     * Description: Misource landing page
  700.     * @Route("/trendingUpdate",name="trendingUpdate");
  701.     */
  702.     public function trendingUpdateAction(Request $request){
  703.         $virtualProducts = DataObject\Product::getById($request->get('productId'));
  704.         $trending = $virtualProducts->getTrending();
  705.         if ($trending >= 0) {
  706.             $trending = $trending + 1;
  707.         } else {
  708.             $trending = 1;
  709.         }
  710.         $virtualProducts->setTrending($trending);
  711.         $virtualProducts->save();
  712.         $virtualProducts->setPublished(true);
  713.        exit;
  714.     }
  715.      /**
  716.      * @Route("/saveSalesCampaignSequence", name="saveSalesCampaignSequence")
  717.      *
  718.      * @param Request $request
  719.      * @return success or error msg
  720.      */
  721.     public function saveSalesCampaignSequence(Request $request)
  722.     {
  723.         $productIds = $request->get('prodData');
  724.         $salesId    = $request->get('salesId');
  725.         
  726.         $prodArray  = array_filter(explode(',',$productIds)); 
  727.         if(!empty($prodArray) && $salesId){ 
  728.             $salesCampaignData = SalesCampaign::getById($salesId, ["force" => true]); 
  729.             $productIdArray = [];  
  730.             if($salesCampaignData){ 
  731.                 for($i=0;$i<count($prodArray);$i++){  
  732.                     foreach ($salesCampaignData->getProducts() as $v) {
  733.                         if ($prodArray[$i] == $v->getId()){ 
  734.                             $productIdArray[] = $v;
  735.                         }
  736.                     }
  737.                 }
  738.                 $salesCampaignData->setProducts($productIdArray); 
  739.                 $salesCampaignData->save();
  740.             }
  741.         }
  742.         return new Response(json_encode(array("status" => "success", 'code' => "400", "message" => " Sales Campaign product sequenced successfully")));
  743.     }
  744.      /**
  745.      * Index page for account - it is restricted to ROLE_USER via security annotation
  746.      *
  747.      * @Route("/newPage", name="newPage")
  748.      *
  749.      * @param UserInterface|null $user
  750.      * @return array
  751.      */
  752.     public function newPageAction(Request $request, UserInterface $user = null, AuthenticationUtils $authenticationUtils, SessionInterface $session)
  753.     {
  754.         if(!$this->editmode) {
  755.             if ($user && $this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  756.                 return $this->redirectToRoute('home');
  757.             }
  758.         }
  759.         $categoriesListing = new Category\Listing();
  760.         $catagories = $categoriesListing->load();
  761.         $firstLavelCatagory = [];
  762.         foreach($catagories as $category){
  763.             if($category->getParent()->getType()=='folder'){
  764.                 array_push($firstLavelCatagory,$category);
  765.             }
  766.         }
  767.         $object = new SupplierCompany();
  768.         $markets = $object->getClass()->getFieldDefinition("markets");
  769.         $marketOptions = $markets->getOptions();
  770.         $companyType = $object->getClass()->getFieldDefinition("companyType");
  771.         $companyTypeOptions = $companyType->getOptions();
  772.         $salesCampaignListing = new SalesCampaign\Listing();
  773.         $salesCampaignListing->setCondition("isActive = ?", 1);
  774.         // $salesCampaignListing->setOrderKey("o_creationDate");
  775.         // $salesCampaignListing->setOrder("desc");
  776.         $salesCampaignListing->setOrderKey("sequenceNumber");
  777.         $salesCampaignListing->setOrder("ASC");
  778.         $salesCampaignListing->setUnpublished(false);
  779.         $salesCampaignListing->load();
  780.         $complianceListing = new Compliance\Listing();
  781.         $complianceListing->load();
  782.         $portListing = new Port\Listing();
  783.         $portListing->load();
  784.         // get the login error if there is one
  785.         $error = $authenticationUtils->getLastAuthenticationError();
  786.         // to load the token to prepopulate the registration form with account data.
  787.         if ($error instanceof AccountNotLinkedException) {
  788.             // this can be anything - for simplicity we just use an UUID as it is unique and random
  789.             $registrationKey = (string) Uuid::uuid4();
  790.           //  $oAuthHandler->saveToken($registrationKey, $error->getToken());
  791.             return $this->redirectToRoute('account-register', [
  792.                 'registrationKey' => $registrationKey
  793.             ]);
  794.         }
  795.         // last username entered by the user
  796.         $lastUsername = $authenticationUtils->getLastUsername();
  797.         $formData = [
  798.             '_username' => $lastUsername
  799.         ];
  800.         $form = $this->createForm(LoginFormType::class, $formData, [
  801.             'action' => $this->generateUrl('account-login'),
  802.         ]);
  803.         return [
  804.                 'categories'=>$firstLavelCatagory,
  805.                 'compliances' => $complianceListing,
  806.                 'ports' => $portListing,
  807.                 'marketOptions' => $marketOptions,
  808.                 'companyTypeOptions' => $companyTypeOptions,
  809.                 'salesCampaign' => $salesCampaignListing,
  810.                 'form' => $form->createView(),
  811.                 'error' => $error,
  812.                 'dClass' => 'display:none;'
  813.             ];
  814.     }
  815.      /**
  816.      *  Description:- Customer Documents
  817.      * 
  818.      * @Route("/user-documents" , name="user-documents");
  819.      * @param Request $request
  820.      * 
  821.     */
  822.      
  823.     public function documents(Request $request)
  824.     {
  825.         try {
  826.             // Check if customer session exists and is an object
  827.             if (!isset($_SESSION['_pimcore_admin']['customer']) || !is_object($_SESSION['_pimcore_admin']['customer'])) {
  828.                 throw new \Exception("Customer session data is invalid or missing.");
  829.             }
  830.             $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
  831.             $customerObj = Customer::getById($customer->getId());
  832.             // Check if customer object is retrieved successfully
  833.             if (!$customerObj instanceof Customer) {
  834.                 throw new \Exception("Customer not found for the given ID: " . ($customer->getId() ?? 'null'));
  835.             }
  836.             $isAbleToComment = $customerObj->getAbleToComment();
  837.             $isAccountManager = $customerObj->getIsAccountManager();
  838.             $customerID = $customerObj->getId();
  839.             // Check if company exists before accessing getKeyAccountManager
  840.             $accountManagers = null;
  841.             $company = $customerObj->getCompany();
  842.             if ($company) {
  843.                 $accountManagers = $company->getKeyAccountManager();
  844.             } else {
  845.                 \Pimcore\Log\Simple::log('documents', "Company not found for customer ID: " . $customerID);
  846.             }
  847.             if ($isAccountManager) {
  848.                 $allUsers = GeneralHelper::getAccountManagers($customerID, "NoDocument", true);
  849.                 // $allCustomers = $allUsers['companyWiseUsers'] ?? [];
  850.                 $allSuppliers = $allUsers['companyWiseSuppliers'] ?? [];
  851.                 $allInternalUsers = $allUsers['allInternalUsers'] ?? [];
  852.                 $allBuyers = GeneralHelper::getAllBuyersHavingKeyAccountManagers($customerID, "NoDocument", true);
  853.                 $allCustomers = $allBuyers['companyWiseUsers'] ?? [];
  854.         
  855.             }
  856.             // $filteredGroups = [];
  857.             // foreach ($allCustomers as $companyName => $group) {
  858.             //     if (is_array($group)) {
  859.             //         $filteredCustomers = [];
  860.             //         foreach ($group as $cust) {
  861.             //             $company = $cust->getCompany();
  862.             //             $keyAccountManagers = $company ? $company->getKeyAccountManager() : [];
  863.             //             $isCurrentUserKAM = false;
  864.             //             if (!empty($keyAccountManagers)) {
  865.             //                 foreach ($keyAccountManagers as $kam) {
  866.             //                     if ($kam->getId() == $customerID) {
  867.             //                         $isCurrentUserKAM = true;
  868.             //                         break;
  869.             //                     }
  870.             //                 }
  871.             //             }
  872.             //             if ($isCurrentUserKAM) {
  873.             //                 $filteredCustomers[] = $cust;
  874.             //             }
  875.             //         }
  876.             //         if (!empty($filteredCustomers)) {
  877.             //             $filteredGroups[$companyName] = $filteredCustomers;
  878.             //         }
  879.             //     }
  880.             // }
  881.             // $allCustomers = $filteredGroups;
  882.             
  883.             $filteredSupplierGroups = [];
  884.             foreach ($allSuppliers as $companyName => $group) {
  885.                 if (is_array($group)) {
  886.                     $filteredSuppliers = [];
  887.                     foreach ($group as $supplier) {
  888.                         $company = $supplier->getCompany();
  889.                         $keyAccountManagers = $company ? $company->getKeyAccountManager() : [];
  890.                         $isCurrentUserKAM = false;
  891.                         if (!empty($keyAccountManagers)) {
  892.                             foreach ($keyAccountManagers as $kam) {
  893.                                 if ($kam->getId() == $customerID) {
  894.                                     $isCurrentUserKAM = true;
  895.                                     break;
  896.                                 }
  897.                             }
  898.                         }
  899.                         if ($isCurrentUserKAM) {
  900.                             $filteredSuppliers[] = $supplier;
  901.                         }
  902.                     }
  903.                     if (!empty($filteredSuppliers)) {
  904.                         $filteredSupplierGroups[$companyName] = $filteredSuppliers;
  905.                     }
  906.                 }
  907.             }
  908.             $allSuppliers = $filteredSupplierGroups;
  909.             
  910.             $productServices = new ProductServices();
  911.             $buyerAccountLoginsArr = $isAbleToComment ? $productServices->getAllBuyerAccounts() : [];
  912.             if ($request->get('docUser')) {
  913.                 $parts = explode("/", $request->get('docUser'));
  914.                 $customerID = $parts[0] ?? null;
  915.                 $boardType = $parts[1] ?? null;
  916.                 if ($customerID) {
  917.                     $customerObj = Customer::getById($customerID);
  918.                     if (!$customerObj instanceof Customer) {
  919.                         throw new \Exception("Customer not found for ID: " . $customerID);
  920.                     }
  921.                     $companyName = $customerObj->getCompany() ? $customerObj->getCompany()->getName() : null;
  922.                     $customerName = trim($customerObj->getFirstName() . " " . $customerObj->getLastName()) ?: null;
  923.                 } else {
  924.                     throw new \Exception("Invalid docUser parameter format.");
  925.                 }
  926.             }
  927.             $allDocuments = [];
  928.             $currentSite = $GLOBALS['site'] ?? (\Pimcore\Model\Site::isSiteRequest() ? \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey() : null);
  929.             $businessUnit = ($currentSite == "NuFind") ? "NuFind" : "3S";
  930.             $subTypeMap = [
  931.                 'productGuidesSubTypes' => 'ProductGuides',
  932.                 'buyingGuidesSubTypes' => 'BuyingGuides',
  933.                 'coreInstructionsSubTypes' => 'CoreInstructions',
  934.                 'policiesSubTypes' => 'Policies'
  935.             ];
  936.             if ($request->get('parentId') && $request->get('id')) {
  937.                 $parentId = $request->get('parentId');
  938.                 $subCategoryId = $request->get('id');
  939.                 $subType = $subTypeMap[$parentId] ?? null;
  940.                 if ($subType) {
  941.                     $parentMethodName = 'get' . ucfirst($parentId) . 'Documents';
  942.                     $subTypeMethodName = 'get' . ucfirst($subType);
  943.                     $customerDocuments = $customerObj->$parentMethodName();
  944.                     if ($customerDocuments) {
  945.                         foreach ($customerDocuments as $document) {
  946.                             if ($document && $document->getBusinessUnit() === $businessUnit && $document->$subTypeMethodName() === $subCategoryId) {
  947.                                 $this->addAttachmentsToDocuments($document, $allDocuments);
  948.                             }
  949.                         }
  950.                     }
  951.                 }
  952.             } else {
  953.                 foreach ($subTypeMap as $parentId => $subType) {
  954.                     $methodName = 'get' . ucfirst($parentId) . 'Documents';
  955.                     if (method_exists($customerObj, $methodName)) {
  956.                         $customerDocuments = $customerObj->$methodName();
  957.                         if ($customerDocuments) {
  958.                             foreach ($customerDocuments as $document) {
  959.                                 if ($document && $document->getBusinessUnit() === $businessUnit) {
  960.                                     $this->addAttachmentsToDocuments($document, $allDocuments);
  961.                                 }
  962.                             }
  963.                         }
  964.                     } else {
  965.                         \Pimcore\Log\Simple::log('documents', "Method $methodName does not exist in class " . get_class($customerObj));
  966.                     }
  967.                 }
  968.             }
  969.             krsort($allDocuments);
  970.             $paginator = new Paginator($allDocuments);
  971.             $paginator->setCurrentPageNumber($request->get('page'));
  972.             $paginator->setItemCountPerPage(5);
  973.             $paginator->setPageRange(5);
  974.             return [
  975.                 'customerObj' => $customerObj,
  976.                 'buyerAccountLogins' => $buyerAccountLoginsArr,
  977.                 'userArray' => $allCustomers ?? [],
  978.                 'supplierArray' => $allSuppliers ?? [],
  979.                 'allInternalUsersArray' => $allInternalUsers ?? [],
  980.                 'paginationVariables' => $paginator->getPages('Sliding'),
  981.                 'isAccountManager' => $isAccountManager,
  982.                 'allDocument' => $paginator,
  983.                 'boardType' => $boardType ?? "",
  984.                 'companyName' => $companyName ?? "",
  985.                 'customerName' => $customerName ?? "",
  986.                 'accountManagers' => $accountManagers ?? []
  987.             ];
  988.         } catch (\Exception $e) {
  989.             \Pimcore\Log\Simple::log('documents', $e->getMessage());
  990.             // return new \Symfony\Component\HttpFoundation\Response("Error: " . $e->getMessage(), 500);
  991.             return $this->redirectToRoute('landing');
  992.         }
  993.     }  
  994.     /* older code dated on 21/7/2025
  995.     public function documents(Request $request)
  996.     {
  997.         try {
  998.             $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
  999.             $customerObj = Customer::getById($customer->getId());
  1000.             $isAbleToComment = $customerObj->getAbleToComment();
  1001.             $isAccountManager = $customerObj->getIsAccountManager();
  1002.             $customerID = $customerObj->getId();
  1003.             // $accountManagers = $customerObj->getCompany()->getAccountManager();
  1004.             $accountManagers = $customerObj->getCompany()->getKeyAccountManager();
  1005.             if ($isAccountManager) {
  1006.                 $allUsers = GeneralHelper::getAccountManagers($customerID, "NoDocument", true);
  1007.                 $allCustomers = $allUsers['companyWiseUsers'];
  1008.                 $allSuppliers = $allUsers['companyWiseSuppliers'];
  1009.                 $allInternalUsers = $allUsers['allInternalUsers'];
  1010.             }
  1011.             $productServices = new ProductServices();
  1012.             $buyerAccountLoginsArr = $isAbleToComment ? $productServices->getAllBuyerAccounts() : [];
  1013.             if ($request->get('docUser')) {
  1014.                 $parts = explode("/", $request->get('docUser'));
  1015.                 $customerID = $parts[0];
  1016.                 $boardType = $parts[1];
  1017.                 $customerObj = Customer::getById($customerID);
  1018.                 $companyName = $customerObj->getCompany()->getName();
  1019.                 $customerName = $customerObj->getFirstName() . " " . $customerObj->getLastName();
  1020.             }
  1021.             $allDocuments = [];
  1022.             $currentSite = $GLOBALS['site'] ?? (\Pimcore\Model\Site::isSiteRequest() ? \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey() : null);
  1023.             $businessUnit = ($currentSite == "NuFind") ? "NuFind" : "3S";
  1024.             $subTypeMap = [
  1025.                 'productGuidesSubTypes' => 'ProductGuides',
  1026.                 'buyingGuidesSubTypes' => 'BuyingGuides',
  1027.                 'coreInstructionsSubTypes' => 'CoreInstructions',
  1028.                 'policiesSubTypes' => 'Policies'
  1029.             ];
  1030.             if ($request->get('parentId') && $request->get('id')) {
  1031.                 $parentId = $request->get('parentId');
  1032.                 $subCategoryId = $request->get('id');
  1033.                 $subType = $subTypeMap[$parentId] ?? null;
  1034.                 if ($subType) {
  1035.                     $parentMethodName = 'get' . ucfirst($parentId) . 'Documents';
  1036.                     $subTypeMethodName = 'get' . ucfirst($subType);
  1037.                     $customerDocuments = $customerObj->$parentMethodName();
  1038.                     if ($customerDocuments) {
  1039.                         foreach ($customerDocuments as $document) {
  1040.                             if ($document->getBusinessUnit() === $businessUnit && $document->$subTypeMethodName() === $subCategoryId) {
  1041.                                 $this->addAttachmentsToDocuments($document, $allDocuments);
  1042.                             }
  1043.                         }
  1044.                     }
  1045.                 }
  1046.             } else {
  1047.                 foreach ($subTypeMap as $parentId => $subType) {
  1048.                     $methodName = 'get' . ucfirst($parentId) . 'Documents';
  1049.                     if (method_exists($customerObj, $methodName)) {
  1050.                         $customerDocuments = $customerObj->$methodName();
  1051.                         if ($customerDocuments) {
  1052.                             foreach ($customerDocuments as $document) {
  1053.                                 if ($document->getBusinessUnit() === $businessUnit) {
  1054.                                     $this->addAttachmentsToDocuments($document, $allDocuments);
  1055.                                 }
  1056.                             }
  1057.                         }
  1058.                     } else {
  1059.                         \Pimcore\Log\Simple::log('documents', "Method $methodName does not exist in class " . get_class($customerObj));
  1060.                     }
  1061.                 }
  1062.             }
  1063.             krsort($allDocuments);
  1064.             $paginator = new Paginator($allDocuments);
  1065.             $paginator->setCurrentPageNumber($request->get('page'));
  1066.             $paginator->setItemCountPerPage(5);
  1067.             $paginator->setPageRange(5);
  1068.             return [
  1069.                 'customerObj' => $customerObj,
  1070.                 'buyerAccountLogins' => $buyerAccountLoginsArr,
  1071.                 'userArray' => $allCustomers ?? [],
  1072.                 'supplierArray' => $allSuppliers ?? [],
  1073.                 'allInternalUsersArray' => $allInternalUsers ?? [],
  1074.                 'paginationVariables' => $paginator->getPages('Sliding'),
  1075.                 'isAccountManager' => $isAccountManager,
  1076.                 'allDocument' => $paginator,
  1077.                 'boardType' => $boardType ?? "",
  1078.                 'companyName' => $companyName ?? "",
  1079.                 'customerName' => $customerName ?? "",
  1080.                 'accountManagers' => $accountManagers
  1081.             ];
  1082.         } catch (\Exception $e) {
  1083.             \Pimcore\Log\Simple::log('documents', $e->getMessage());
  1084.             return new \Symfony\Component\HttpFoundation\Response("Error: " . $e->getMessage(), 500);
  1085.         }
  1086.     }
  1087.     */    
  1088.     private function addAttachmentsToDocuments($document, &$allDocuments)
  1089.     {
  1090.         if ($document->getAttachments()) {
  1091.             foreach ($document->getAttachments() as $attachment) {
  1092.                 $documentId = $attachment->getId();
  1093.                 $asset = Asset::getById($documentId);
  1094.                 if ($asset) {
  1095.                     $allDocuments[$documentId] = $asset;
  1096.                 }
  1097.             }
  1098.         }
  1099.     }
  1100.     // public function documents(Request $request)
  1101.     // { 
  1102.     //     try {
  1103.     //         $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;    
  1104.     //         $customerObj = "";          
  1105.     //         $isAbleToComment = false;
  1106.     //         $customerId = $customer->getId();
  1107.     //         if (!empty($customer)) {
  1108.     //             $customerObj = Customer::getById($customerId);         
  1109.     //             $isAbleToComment = $customerObj->getAbleToComment(); 
  1110.     //             $isAccountManager=  $customerObj->getIsAccountManager(); 
  1111.     //             $customerID = $customerObj->getId();
  1112.     //             if($isAccountManager){
  1113.                     
  1114.     //                 $allUsers = GeneralHelper::getAccountManagers($customerId,"NoDocument", true);
  1115.                     
  1116.     //                 $allCustomers = $allUsers['companyWiseUsers'];
  1117.     //                 $allSuppliers = $allUsers['companyWiseSuppliers'];
  1118.     //                 $allInternalUsers = $allUsers['allInternalUsers'];
  1119.                     
  1120.     //             } 
  1121.     //         }
  1122.     //         $productServices = new ProductServices();
  1123.     //         //ALL Buyer Account
  1124.     //         $buyerAccountLoginsArr = [];
  1125.     //         if($isAbleToComment){
  1126.     //             $buyerAccountLoginsArr = $productServices->getAllBuyerAccounts();
  1127.     //         }     
  1128.     //         if($request->get('docUser')){
  1129.     //             $customerID = $request->get('docUser');
  1130.                 
  1131.                 
  1132.     //             $parts = explode("/", $customerID);
  1133.     //             $customerID = $parts[0];
  1134.     //             $boardType = $parts[1];
  1135.     //             $customerId = $customerID;
  1136.     //             $docUserData =  Customer::getById($customerID);
  1137.     //             $customerObj =  $docUserData;
  1138.     //             $companyName = $docUserData->getCompany()->getName();
  1139.     //             $customerName = $docUserData->getFirstName()." ".$customerObj->getLastName();
  1140.     //         }           
  1141.     //         //LOGIC NEED TO WRITE HERE IF docUser exists then need to take this id
  1142.     //         $allDocuments = [];
  1143.     //         // $db = \Pimcore\Db::get();
  1144.     //         $currentSite = $GLOBALS['site'];
  1145.     //         if(!$currentSite){
  1146.     //             if (\Pimcore\Model\Site::isSiteRequest()) {            
  1147.     //                 $currentSite = \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey();
  1148.     //             }
  1149.     //         }
  1150.     //         $businessUnit = ($currentSite == "NuFind") ? "NuFind" : "3S";
  1151.     //         $subTypeMap = [
  1152.     //             'productGuidesSubTypes' => 'ProductGuides',
  1153.     //             'buyingGuidesSubTypes' => 'BuyingGuides',
  1154.     //             'coreInstructionsSubTypes' => 'CoreInstructions',
  1155.     //             'policiesSubTypes' => 'Policies'
  1156.     //         ];
  1157.     //         if($request->get('parentId') && $request->get('id')){
  1158.     //             $parentId =$request->get('parentId');
  1159.     //             $subCategoryId = $request->get('id');
  1160.     //             $subType = isset($subTypeMap[$parentId]) ? $subTypeMap[$parentId] : null;
  1161.     //             if ($subType) {
  1162.     //                 $parentMethodName = 'get' . ucfirst($parentId) . 'Documents';
  1163.     //                 $subTypeMethodName = 'get' . ucfirst($subType);
  1164.     //                 // dd($subTypeMethodName);
  1165.     //                 $customerDocuments = $customerObj->$parentMethodName();
  1166.     //                 if ($customerDocuments) {
  1167.     //                     foreach ($customerDocuments as $document) {
  1168.     //                         if ($document->getBusinessUnit() === $businessUnit && $document->$subTypeMethodName() === $subCategoryId) {
  1169.     //                             if ($document->getAttachments()) {
  1170.     //                                 foreach ($document->getAttachments() as $attachment) {
  1171.     //                                     $documentId = $attachment->getId();
  1172.     //                                     $asset = Asset::getById($documentId);
  1173.     //                                     if ($asset) {
  1174.     //                                         $allDocuments[$documentId] = $asset;
  1175.     //                                     }
  1176.     //                                 }
  1177.     //                             }
  1178.     //                         }
  1179.     //                     }
  1180.     //                 }
  1181.     //             }
  1182.     //             krsort($allDocuments);
  1183.     //         }
  1184.     //         else{
  1185.     //             foreach ($subTypeMap as $parentId => $subType) {
  1186.     //                 $methodName = 'get' . ucfirst($parentId) . 'Documents';
  1187.     //                 $customerDocuments = $customerObj->$methodName();
  1188.                 
  1189.     //                 if ($customerDocuments) {
  1190.     //                     foreach ($customerDocuments as $document) {
  1191.     //                         if ($document->getBusinessUnit() === $businessUnit) {
  1192.     //                             if ($document->getAttachments()) {
  1193.     //                                 foreach ($document->getAttachments() as $attachment) {
  1194.     //                                     $documentId = $attachment->getId();
  1195.     //                                     $asset = Asset::getById($documentId);
  1196.     //                                     if ($asset) {
  1197.     //                                         $allDocuments[$documentId] = $asset;
  1198.     //                                     }
  1199.     //                                 }
  1200.     //                             }
  1201.     //                         }
  1202.     //                     }
  1203.     //                 }
  1204.     //             }         
  1205.     //             krsort($allDocuments);
  1206.     //         }
  1207.                 
  1208.     //         $paginator = new Paginator($allDocuments);
  1209.     //         $paginator->setCurrentPageNumber($request->get('page'));
  1210.     //         $paginator->setItemCountPerPage(5);
  1211.     //         $pageLimit = 5;
  1212.             
  1213.     //         $paginator->setPageRange($pageLimit);           
  1214.             
  1215.     //         return [
  1216.     //             'customerObj'=>$customerObj,
  1217.     //             'buyerAccountLogins' => $buyerAccountLoginsArr,
  1218.     //             'userArray' => $allCustomers,
  1219.     //             'supplierArray' => $allSuppliers,
  1220.     //             'allInternalUsersArray' => $allInternalUsers,
  1221.     //             'paginationVariables' => $paginator->getPages('Sliding'),
  1222.     //             'isAccountManager' => $isAccountManager,
  1223.     //             'allDocument' => $paginator,
  1224.     //             'boardType' =>$boardType ?? "",
  1225.     //             'companyName' =>$companyName ?? "",
  1226.     //             'customerName' =>$customerName ?? "",
  1227.     //         ];
  1228.     //     } catch (\Exception $e) {
  1229.     //         return new \Symfony\Component\HttpFoundation\Response("Error: " . $e->getMessage(), 500);
  1230.     //     }
  1231.     // }
  1232.     /**
  1233.      *  Description:- Global Documents
  1234.      * 
  1235.      * @Route("/global-documents" , name="global-documents");
  1236.      * @param Request $request
  1237.      * 
  1238.     */ 
  1239.     public function globalDocuments()
  1240.     { 
  1241.         $websiteConfig = \Pimcore\Config::getWebsiteConfig();
  1242.         $globalDocumentUser = $websiteConfig->get('GLOBAL_DOCUMENT_USER');
  1243.             
  1244.         $customerObj = "";          
  1245.         if ($globalDocumentUser) {
  1246.             $customerId = $globalDocumentUser->getId();
  1247.             $customerObj = Customer::getById($customerId);            
  1248.         }
  1249.         return [
  1250.             'customerObj'=>$customerObj            
  1251.         ];
  1252.     }
  1253.     /**
  1254.      *  Description:- Admin PDF Generate  
  1255.      *    
  1256.      * @Route("/global/pdf/{wishlistId}" , name="admin-custom-pdf-wishlist");
  1257.      * @param Request $request
  1258.      * 
  1259.     */ 
  1260.     public function adminPDFGenerateAction(Request $request, Factory $ecommerceFactory, $wishlistId)
  1261.     {
  1262.         $websiteConfig = \Pimcore\Config::getWebsiteConfig();
  1263.         $globalDocumentUser = $websiteConfig->get('GLOBAL_DOCUMENT_USER');
  1264.         $_SESSION['_pimcore_admin']['customer'] = $globalDocumentUser;
  1265.         
  1266.         $viewModel = new ViewModel();
  1267.         $productServices = new ProductServices();
  1268.         $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
  1269.         $viewModel->wishlistId = $wishlistId;
  1270.         $wishlistData = Wishlist::getById($wishlistId, ["force" => true]);
  1271.         if ($wishlistData) {
  1272.             $viewModel->wishlistName = $wishlistData->getLable();
  1273.             $viewModel->wishlistComment = $wishlistData->getComment();
  1274.             $wishlistProduct = [];
  1275.             $wishlistProductData = "";
  1276.             $viewModel->isPDF  =    'yes';
  1277.             $wishlistProductData = $wishlistData->getProducts();
  1278.             if (!empty($wishlistProductData)) {
  1279.                 foreach ($wishlistProductData as $k => $v) {
  1280.                     $wishlistProduct[] = $v->getId();
  1281.                 }
  1282.             }
  1283.             $totalCount =   count($wishlistProduct);
  1284.             $productListing = $productServices->getWishlistProductListing($viewModel, $ecommerceFactory, $request, $wishlistProduct,'yes');
  1285.             if (empty($productListing)) {
  1286.                 $viewModel->results = [];
  1287.             }
  1288.         } else {
  1289.             $viewModel->results = [];
  1290.         }
  1291.         $accountManagers = GeneralHelper::myAccountManagers($customer);
  1292.         
  1293.         $currentSite = $GLOBALS['site'];
  1294.         if(!$currentSite){
  1295.             if (\Pimcore\Model\Site::isSiteRequest()) {            
  1296.                 $currentSite = \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey();
  1297.             }
  1298.         }
  1299.         $params = [];
  1300.         $viewModel->type = "wishlist";
  1301.         $viewModel->mainTitle = $viewModel->wishlistName ?? "";
  1302.         if($currentSite == "3SWebsite"){
  1303.             $html = $this->renderView('@Global/default/3SWebsite/content.html.twig', array('wishlistId' => $viewModel->getAllParameters()['wishlistId'], 'results' => $viewModel->getAllParameters()['results'], 'mainTitle' => $wishlistData->getLable(), 'wishlistComment' => $wishlistData->getComment(),'totalCount' => $totalCount, 'accountManagers'=>$accountManagers,"type"=>"wishlist"));
  1304.         }
  1305.         else{
  1306.             $html = $this->renderView('@Global/product/wishlistCatalog.html.twig', array('wishlistId' => $viewModel->getAllParameters()['wishlistId'], 'results' => $viewModel->getAllParameters()['results'], 'wishlistName' => $wishlistData->getLable(), 'wishlistComment' => $wishlistData->getComment(),'totalCount' => $totalCount,'accountManagers'=>$accountManagers,"type"=>"wishlist"));
  1307.         }
  1308.         $fileName = 'wishlist-' . $wishlistId . '.pdf';
  1309.         $headerCatalogName = urlencode($wishlistData->getLable());
  1310.         $adapter = \Pimcore\Web2Print\Processor::getInstance();
  1311.         $adapterString = "--print-media-type --page-size A4 --orientation landscape --margin-left 0mm --margin-right 0mm --margin-top 1cm --margin-bottom 1cm  --header-html ".\Pimcore\Tool::getHostUrl()."/global-pdf-header/{$currentSite}/?headerName='".( $headerCatalogName ?? '')."' --footer-html ".\Pimcore\Tool::getHostUrl()."/global-pdf-footer/{$currentSite}/";        
  1312.         $adapter->setOptions($adapterString);
  1313.         return new \Symfony\Component\HttpFoundation\Response($adapter->getPdfFromString($html, $params), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename=' . $fileName)); //direct download
  1314.     }
  1315.     /**
  1316.      * @Route("/legal", name="legal")
  1317.      * 
  1318.      * @param Request $request
  1319.      *
  1320.      * @return array|\Symfony\Component\HttpFoundation\Response
  1321.      */
  1322.     public function legalAction(Request $request){
  1323.         $viewModel = new ViewModel();
  1324.         $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
  1325.         $viewModel->CDN_URL = PIMCORE_CDN_BASEURL;
  1326.         $formData = [
  1327.             '_username' => $lastUsername
  1328.         ];
  1329.         $form = $this->createForm(LoginFormType::class, $formData, [
  1330.             'action' => $this->generateUrl('account-login'),
  1331.         ]);
  1332.         $viewModel->form = $form->createView();
  1333.         if(!empty($customer)){
  1334.             $viewModel->customer = $customer;
  1335.         }
  1336.         $viewModel->editmode = $this->editmode;
  1337.         
  1338.         return $viewModel->getAllParameters();
  1339.         return $this->render('@Global/default/legal.html.twig',$viewModel->getAllParameters());
  1340.     }
  1341.     /**
  1342.      * @Route("/salesxls")
  1343.      *
  1344.      * @param Request $request
  1345.      * @return success or error msg
  1346.      */
  1347.     public function salesXlsExport(Request $request){
  1348.         $salesCampaignId = $request->get("salesCampaignId");
  1349.         $object     = DataObject\SalesCampaign::getById($salesCampaignId);
  1350.        
  1351.         if($object){
  1352.             $productData= $object->getProducts();
  1353.             $title=$object->getTitle();
  1354.             
  1355.             $spreadsheet = new Spreadsheet();
  1356.             // if($exportType=='CSV'){
  1357.             //     $Excel_writer = new Csv($spreadsheet);
  1358.             // }else{
  1359.                 $Excel_writer = new Xlsx($spreadsheet);
  1360.             // }
  1361.             
  1362.             
  1363.             $spreadsheet->setActiveSheetIndex(0);
  1364.             $activeSheet = $spreadsheet->getActiveSheet();
  1365.             
  1366.             $activeSheet->setCellValue('A1', 'SKU ID');
  1367.             $activeSheet->setCellValue('B1', 'EAN Code');
  1368.             $activeSheet->setCellValue('C1', 'Factory Item No');
  1369.             $activeSheet->setCellValue('D1', 'Product Name');
  1370.             $activeSheet->setCellValue('E1', 'Supplier');
  1371.             $activeSheet->setCellValue('F1', 'Category');
  1372.             $activeSheet->setCellValue('G1', 'Material');
  1373.             $activeSheet->setCellValue('H1', 'Product Image');
  1374.             if($productData){
  1375.                 $i = 2;
  1376.                 foreach($productData as $key => $prodValue){
  1377.                     $material   = [];
  1378.                     if ($prodValue->getType() == 'variant') {
  1379.                         $prodValue = $prodValue->getParent();
  1380.                     }
  1381.                     if($prodValue->getMaterial()){
  1382.                         foreach($prodValue->getMaterial() as $mValue){
  1383.                             $materialObject     = DataObject\Material::getById($mValue);
  1384.                             if($materialObject){
  1385.                                 $material[]         = $materialObject->getName();
  1386.                             }
  1387.                         }
  1388.                         $materialValue          = implode(',',$material);
  1389.                     }
  1390.                     $mainImagedata  = $prodValue->getMainImage();
  1391.                     if($mainImagedata){ 
  1392.                         $asset      =   Asset::getById($mainImagedata->getId());
  1393.                         if (!empty($asset)) { 
  1394.                             $pathToThumbnail = $asset->getThumbnail("productListImageNewPng")->getPath(); 
  1395.                         }
  1396.                     }
  1397.                     if($prodValue->getCategory()){
  1398.                         $catArr     =   array_slice(explode('/',$prodValue->getCategory()), 2); 
  1399.                         $newCatValue=   implode('/',$catArr);
  1400.                     }
  1401.                     $activeSheet->setCellValue('A'.$i , $prodValue->getId());
  1402.                     $activeSheet->setCellValue('B'.$i , $prodValue->getEanCode());
  1403.                     $activeSheet->setCellValue('C'.$i , $prodValue->getProductCode());
  1404.                     $activeSheet->setCellValue('D'.$i , $prodValue->getProductName());
  1405.                     $activeSheet->setCellValue('E'.$i , $prodValue->getSupplier()->getName());
  1406.                     $activeSheet->setCellValue('F'.$i , $newCatValue);
  1407.                     $activeSheet->setCellValue('G'.$i , $materialValue);
  1408.                         $pathToThumbnail = str_replace(' ', '%20', $pathToThumbnail);
  1409.                         $srcImage = imagecreatefrompng($pathToThumbnail);
  1410.                         imagealphablending($srcImage, false);
  1411.                         imagesavealpha($srcImage, true);
  1412.                         $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing();
  1413.                         $drawing->setImageResource($srcImage);
  1414.                         $drawing->setCoordinates('H'.$i);
  1415.                         $drawing->setWidthAndHeight(200, 200);
  1416.                         $drawing->setRenderingFunction(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::RENDERING_PNG);
  1417.                         $drawing->setMimeType(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_DEFAULT);
  1418.                         $drawing->setOffsetX(110);
  1419.                         $drawing->setWorksheet($spreadsheet->getActiveSheet());
  1420.                         $spreadsheet->getActiveSheet()->getRowDimension($i)->setRowHeight(170);
  1421.                         $spreadsheet->getActiveSheet()->getColumnDimension('H')->setWidth('50');
  1422.                         foreach (range('A', 'G') as $letra) {            
  1423.                             $spreadsheet->getActiveSheet()->getColumnDimension($letra)->setAutoSize(true);
  1424.                         }
  1425.                    
  1426.                     $i++;
  1427.                 }
  1428.             }
  1429.             if($exportType=='CSV'){
  1430.                 $filename = $title.'_'.$salesCampaignId.'.csv';
  1431.                 header('Content-Type: text/csv');  
  1432.             }else{
  1433.                 $filename = $title.'_'.$salesCampaignId.'.xlsx';
  1434.                 header('Content-Type: application/vnd.ms-excel');
  1435.             }
  1436.             
  1437.             header('Content-Disposition: attachment;filename='.$filename);
  1438.             header('Cache-Control: max-age=0');
  1439.             $Excel_writer->save('salesCampaignExport/'.$filename);
  1440.             $baseUrl    =   \Pimcore\Tool::getHostUrl();
  1441.             return new Response(json_encode(array("status" => "success", 'code' => $code, "message" => $message,"ExportLink" => $baseUrl.'/salesCampaignExport/'.$filename)));
  1442.         } else {
  1443.             return new Response(json_encode(array("status" => "success", 'code' => "400", "message" => "Error")));
  1444.         }
  1445.     }
  1446.     /**
  1447.      * @Route("/salesCampaignPreview/{id}")
  1448.      *
  1449.      * @param Request $request
  1450.      * @return success or error msg
  1451.      */
  1452.     public function salesCampaignPreview(Request $request, Factory $ecommerceFactory, $id)
  1453.     {
  1454.         $viewModel = new ViewModel();
  1455.         $productServices = new ProductServices();
  1456.         $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
  1457.         $viewModel->salesId = $id;
  1458.         $salesData = SalesCampaign::getById($id, ["force" => true]);
  1459.         $viewModel->editmode = $this->editmode;
  1460.         $viewModel->status = true;
  1461.         $formData = [
  1462.             '_username' => $lastUsername
  1463.         ];
  1464.         $form = $this->createForm(LoginFormType::class, $formData, [
  1465.             'action' => $this->generateUrl('account-login'),
  1466.         ]);
  1467.         $viewModel->form = $form->createView();
  1468.         if ($salesData) {
  1469.             $viewModel->salesCampaignName = $salesData->getTitle();
  1470.             $viewModel->salesCampaignComment = $salesData->getShortDescription();
  1471.             $viewModel->isPDF  =    'yes';
  1472.             $salesProduct = [];
  1473.             $salesProductData = "";
  1474.             $salesProductData = $salesData->getProducts();
  1475.             if (!empty($salesProductData)) {
  1476.                 foreach ($salesProductData as $k => $v) {
  1477.                     $salesProduct[] = $v->getId();
  1478.                 }
  1479.             }
  1480.             $viewModel->totalCount =   count($salesProduct);
  1481.             $viewModel->previewFalg =  true;
  1482.             $productListing = $salesData->getProducts();
  1483.             // Preserve the product order configured on the sales campaign.
  1484.             if (empty($productListing)) {
  1485.                 $viewModel->results = [];
  1486.                 $viewModel->status = false;
  1487.             }else{
  1488.                 $viewModel->results = $productListing;
  1489.             }
  1490.             if($salesData->getCampaignType() == 'Lead' && $salesData->getIsPublic() != 1){
  1491.                 $viewModel->isVerified = 0;
  1492.             }
  1493.     
  1494.             if($salesData->getCampaignType() == 'Lead' && $salesData->getAccessCode() == ''){
  1495.                 $viewModel->noAccessCode = 1;
  1496.             }else{
  1497.                 $viewModel->noAccessCode = 0;
  1498.             }
  1499.         } else {
  1500.             $viewModel->results = [];
  1501.         }
  1502.         $accountManagers = GeneralHelper::myAccountManagers($customer);
  1503.         $viewModel->accountManagers = $accountManagers;
  1504.         $currentSite = $GLOBALS['site'];
  1505.         if(!$currentSite){
  1506.             if (\Pimcore\Model\Site::isSiteRequest()) {            
  1507.                 $currentSite = \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey();
  1508.             }
  1509.         }
  1510.         
  1511.         $params = [];
  1512.         $viewModel->type = "salescampaign";
  1513.         $viewModel->mainTitle = $viewModel->salesCampaignName ?? "";
  1514.         if($currentSite == "3SWebsite"){            
  1515.             return $this->render('@Global/default/3SWebsite/content.html.twig', $viewModel->getAllParameters());
  1516.         }
  1517.         else{
  1518.             return $this->render('@Global/default/salesCampaignPreview.html.twig',$viewModel->getAllParameters());
  1519.         }
  1520.         
  1521.     }
  1522.     /**
  1523.      * @Route("/salesCampaignPdf/{salesCampaignId}")
  1524.      *
  1525.      * @param Request $request
  1526.      * @return success or error msg
  1527.      */
  1528.     public function salesCampaignPdfAction(Request $request, Factory $ecommerceFactory, $salesCampaignId)
  1529.     {
  1530.         $viewModel = new ViewModel();
  1531.         $productServices = new ProductServices();
  1532.         $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
  1533.         $viewModel->salesCampaignId = $salesCampaignId;
  1534.         $salesData = SalesCampaign::getById($salesCampaignId, ["force" => true]);
  1535.         if ($salesData) {
  1536.             $viewModel->salesCampaignName = $salesData->getTitle();
  1537.             $viewModel->salesCampaignComment = $salesData->getShortDescription();
  1538.             $viewModel->isPDF  =    'yes';
  1539.             $salesProduct = [];
  1540.             $salesProductData = "";
  1541.             $salesProductData = $salesData->getProducts();
  1542.             if (!empty($salesProductData)) {
  1543.                 foreach ($salesProductData as $k => $v) {
  1544.                     $salesProduct[] = $v->getId();
  1545.                 }
  1546.             }
  1547.             $viewModel->totalCount =   count($salesProduct);
  1548.             $productListing = $salesData->getProducts();
  1549.             /* foreach($productListing as $k=>$v) {
  1550.                 $sort['name'][$k] = $v->getProductName();
  1551.              }
  1552.             array_multisort($sort['name'], SORT_ASC,$productListing); */
  1553.             if (empty($productListing)) {
  1554.                 $viewModel->results = [];
  1555.             }else{
  1556.                 $viewModel->results = $productListing;
  1557.             }
  1558.         } else {
  1559.             $viewModel->results = [];
  1560.         }
  1561.         $accountManagers = GeneralHelper::myAccountManagers($customer);
  1562.         $currentSite = $GLOBALS['site'];
  1563.         if(!$currentSite){
  1564.             if (\Pimcore\Model\Site::isSiteRequest()) {            
  1565.                 $currentSite = \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey();
  1566.             }
  1567.         }
  1568.         $params = [];
  1569.         if($currentSite == "3SWebsite"){            
  1570.             $html = $this->renderView('@Global/default/3SWebsite/content.html.twig', array('salesId' => $viewModel->getAllParameters()['salesId'], 'results' => $viewModel->getAllParameters()['results'], 'mainTitle' => $salesData->getTitle(), 'salesCampaignComment' => $salesData->getShortDescription(),'totalCount' => $totalCount, 'accountManagers'=>$accountManagers,"type"=>"salescampaign"));
  1571.         }
  1572.         else{
  1573.             $html = $this->renderView('@Global/default/salesCampaignPreview.html.twig',array('salesId' => $viewModel->getAllParameters()['salesId'], 'results' => $viewModel->getAllParameters()['results'], 'salesCampaignName' => $salesData->getTitle(), 'salesCampaignComment' => $salesData->getShortDescription(),'totalCount' => $totalCount, 'accountManagers'=>$accountManagers));
  1574.         }
  1575.         $fileName = 'SalesCampaign-' . $salesCampaignId . '.pdf';
  1576.         $headerCatalogName = urlencode($salesData->getTitle());
  1577.         $adapter = \Pimcore\Web2Print\Processor::getInstance();
  1578.         $adapterString = "--print-media-type --page-size A4 --orientation landscape --margin-left 0mm --margin-right 0mm --margin-top 1cm --margin-bottom 1cm  --header-html ".\Pimcore\Tool::getHostUrl()."/global-pdf-header/{$currentSite}/?headerName='".( $headerCatalogName ?? '')."' --footer-html ".\Pimcore\Tool::getHostUrl()."/global-pdf-footer/{$currentSite}/";        
  1579.         $adapter->setOptions($adapterString);
  1580.         return new \Symfony\Component\HttpFoundation\Response($adapter->getPdfFromString($html, $params), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename=' . $fileName)); //direct download
  1581.     }
  1582.      /**
  1583.      * @Route("/loadSubCategory" , name="loadSubCategory")
  1584.      *
  1585.      * @param Request $request
  1586.      * @return success or error msg
  1587.      */
  1588.     public function loadSubCategory(Request $request, Factory $ecommerceFactory)
  1589.     {
  1590.         $category = $request->get('category');
  1591.         $attr = $category.'SubTypes';  
  1592.         $object = new Customer();
  1593.         $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
  1594.         $customerData = $customer->getClass()->getFieldDefinition($attr);
  1595.         $getSubcategory =   $customerData->getChilds()[0]->getOptions();
  1596.         $subcatArray    =   [];
  1597.         foreach($getSubcategory as $subcat){ 
  1598.             $subcatArray[$subcat['value']]    = $subcat['key'];
  1599.         }
  1600.         return new Response(json_encode(array("status" => "success", 'code' => "200", "message" => "subcategory fetched successfully",'subcategoryArray'=>$subcatArray)));
  1601.     }
  1602.     /**
  1603.      * @Route("/addDocuments")
  1604.      *
  1605.      * @param Request $request
  1606.      * @return success or error msg
  1607.      */
  1608.     function addDocumentsFunction(Request $request)
  1609.     {         
  1610.         $userId = $request->get("userId");
  1611.         $docCategory = $request->get("documentCategory"); 
  1612.         $docSubcategory = $request->get("documentSubCategory");
  1613.         $currentSite = $GLOBALS['site'] ?? (\Pimcore\Model\Site::isSiteRequest() ? \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey() : null);
  1614.         $businessUnit = ($currentSite == "NuFind") ? "NuFind" : "3S";       
  1615.         $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
  1616.         if($userId){
  1617.         $customerData = Customer::getById($userId, ["force" => true]);
  1618.         }else{
  1619.         $customerData = Customer::getById($customer->getId(), ["force" => true]);
  1620.         }        
  1621.         if ($customerData) { 
  1622.             $attrKey =   'get'.ucfirst($docCategory).'SubTypesDocuments';
  1623.             $getDocCategory     =   $customerData->$attrKey(); 
  1624.             $setSubCategory  = 'set'.ucfirst($docCategory);
  1625.             $docCollection = ucfirst($docCategory.'SubTypesDocuments');
  1626.             $setDocument = 'set'.$docCollection;
  1627.             $message = "Error";
  1628.             $code = "400";
  1629.              try{                 
  1630.                 $bannerImage = $request->files->get('files');    
  1631.                 if (!empty($bannerImage)) {
  1632.                 $campaignBannerImages = [];
  1633.                 for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
  1634.                     $path = '/Documents/'.$docCategory."/".$docSubcategory."/".$userId;
  1635.                     $folder = \Pimcore\Model\Asset\Service::createFolderByPath($path);                        
  1636.                     $newAsset = new \Pimcore\Model\Asset();
  1637.                     $filename = \Pimcore\Model\Element\Service::getValidKey($bannerImage[$i]->getClientOriginalName(), 'asset');
  1638.                     $filename = $this->getSafeFilename($folder->getRealFullPath(), $filename);
  1639.                     $newAsset->setFilename($filename);
  1640.                     $newAsset->setData(file_get_contents($bannerImage[$i]));
  1641.                     $newAsset->setParentId($folder->getId());                                                                  
  1642.                     if ($newAsset->save()) {
  1643.                         if(!empty($newAsset)){
  1644.                             $campaignBannerImages[] = $newAsset;
  1645.                         }
  1646.                     }
  1647.                 }
  1648.                 } 
  1649.                 $existingDocumentCollectionObj = $getDocCategory ?: new DataObject\Fieldcollection();
  1650.                 $collectionName = 'Pimcore\\Model\\DataObject\\Fieldcollection\\Data\\' . $docCollection;
  1651.                 $documentCollection = new $collectionName();
  1652.                 
  1653.                 $documentCollection->$setSubCategory($docSubcategory);
  1654.                 $documentCollection->setAttachments($campaignBannerImages);
  1655.                 $documentCollection->setBusinessUnit($businessUnit);
  1656.                 $existingDocumentCollectionObj->add($documentCollection);
  1657.                 $customerData->$setDocument($existingDocumentCollectionObj);
  1658.                 $customerData->save();                
  1659.                 $code = "200";
  1660.                 $customerId = $customer->getId();   
  1661.                 $message = 'Documents submitted successfully';              
  1662.              }
  1663.              catch(\Exception $e){                                             
  1664.                  $message = ["message"=>$e->getMessage()];
  1665.                  $code = "400";
  1666.              }            
  1667.              return new Response(json_encode(array("status" => "success", 'code' => $code, "message" => $message)));
  1668.          }
  1669.          else {
  1670.              return new Response(json_encode(array("status" => "success", 'code' => "400", "message" => ["message"=>"Error"])));
  1671.          }
  1672.     }
  1673.     protected function getSafeFilename($targetPath, $filename)
  1674.     {
  1675.         $pathinfo = pathinfo($filename);
  1676.         $originalFilename = $pathinfo['filename'];
  1677.         $originalFileextension = empty($pathinfo['extension']) ? '' : '.' . $pathinfo['extension'];
  1678.         $count = 1;
  1679.         if ($targetPath == '/') {
  1680.             $targetPath = '';
  1681.         }
  1682.         while (true) {
  1683.             if (Asset\Service::pathExists($targetPath . '/' . $filename)) {
  1684.                 $filename = $originalFilename . '_v' . $count . $originalFileextension;
  1685.                 $count++;
  1686.             } else {
  1687.                 return $filename;
  1688.             }
  1689.         }
  1690.     }
  1691.       /**
  1692.      * @Route("/loadDocData" , name="loadDocData")
  1693.      *
  1694.      * @param Request $request
  1695.      * @return success or error msg
  1696.      */
  1697.     function loadDocData(Request $request)
  1698.     { 
  1699.         $docId = $request->get("docId"); 
  1700.         $flag = $request->get("flag");
  1701.         $document = Asset::getById($docId);
  1702.         $versionsArray  = [];
  1703.         if($document) { 
  1704.             if($flag == 'documentVersion'){
  1705.                 $versions = $document->getVersions();   
  1706.                 $versions = \Pimcore\Model\Element\Service::getSafeVersionInfo($versions);
  1707.                 $versions = array_reverse($versions); //reverse array to sort by ID DESC                                              
  1708.                 foreach($versions as $versionObj){                      
  1709.                     $var = \Pimcore\Model\Version::getById($versionObj['id']);                                                                                                   
  1710.                     $asset = $var->loadData();                      
  1711.                     $fileId    =    $var->getId();
  1712.                     $fileDate  =    date('d/m/y', $var->getDate());
  1713.                     $fileName  =    $var->getData()->getFilename();
  1714.                     $path      =    PIMCORE_CDN_BASEURL.'/assets/'.$fileName;
  1715.                     $fileSize  =    $asset->getFileSize(true);
  1716.                     // $modifiedUser = $var->getData()->getUser()->getFirstname();
  1717.                     // $modifyDate   = $var->getData()->getModificationDate();
  1718.                     $versionsArray[] = array('id'=>$fileId,'date'=>$fileDate,'filename' => $fileName,'path' => $asset->getId(), 'fileSize'=> $fileSize);
  1719.                 }                                                   
  1720.                              
  1721.             }else{
  1722.                 $listing = new Note\Listing();
  1723.                 $listing->setCondition('cid LIKE '.$docId);
  1724.                 $listing->load();
  1725.                 $notes = $listing->getNotes();
  1726.                 if(!empty($notes)){
  1727.                     $comment = $notes[0]->getDescription();
  1728.                 }else{
  1729.                     $comment = '';
  1730.                 }
  1731.             }
  1732.         }
  1733.         return new Response(json_encode(array("status" => "success", 'code' => '400', "comment" => $comment,'versions' => $versionsArray)));
  1734.     }
  1735.       /**
  1736.      * @Route("/documentOprations" , name="documentOprations")
  1737.      *
  1738.      * @param Request $request
  1739.      * @return success or error msg
  1740.      */
  1741.     function documentOprations(Request $request)
  1742.      { 
  1743.         $docId = $request->get("docId"); 
  1744.         $flag  = $request->get("flag"); 
  1745.         $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
  1746.         $document = Asset::getById($docId);
  1747.         $files = $request->files->get('files');   
  1748.         $comment = $request->get('commentValue');    
  1749.         if($document) { 
  1750.             if($flag == 'delete'){
  1751.                 $document->delete();
  1752.                 $message =  'Document deleted successfully';
  1753.             }elseif($flag == 'update' && !empty($files)){ 
  1754.                 $document->setData(file_get_contents($files[0]));
  1755.                 $document->save();
  1756.                 $message =  'Document updated successfully';
  1757.             }elseif($flag == 'comment'){
  1758.                 $listing = new Note\Listing();
  1759.                 $listing->setCondition('cid LIKE '.$docId);
  1760.                 $listing->load();
  1761.                 $notes = $listing->getNotes();
  1762.                 if(!empty($notes)){
  1763.                     $notes[0]->setDescription($comment);
  1764.                     $notes[0]->setUser($customer);
  1765.                     $notes[0]->save();
  1766.                 }else{
  1767.                     $note = new \Pimcore\Model\Element\Note();
  1768.                     $note->setElement($document);
  1769.                     $note->setDate(time());
  1770.                     $note->setType("content");
  1771.                     $note->setTitle("Document comment");
  1772.                     $note->setDescription($comment);
  1773.                     $note->setUser($customer);
  1774.                     $note->save();
  1775.                 }
  1776.                 $commentBuyerAccounts = $request->get('commentBuyerAccounts') ?? []; 
  1777.                 //SEND AN EMAIL                     
  1778.                 if(count($commentBuyerAccounts) > 0){                                          
  1779.                     $bodyParams = array('commentDocument' => $comment, 'documentName'=>$document->getFilename());                                        
  1780.                     $mail = new \Pimcore\Mail();
  1781.                     $mail->setIgnoreDebugMode(true);
  1782.                     $mail->setDocument(\Pimcore\Model\Document::getByPath('/'.EMAILDOCUMENT_PATH.'/Emails/Documents/DocumentReviewComments'));                    
  1783.                     $mail->addTo($commentBuyerAccounts);
  1784.                     $mail->setParams($bodyParams);
  1785.                     $mail->setSubject("Document - Review Comments");
  1786.                     /*try{
  1787.                         $currentSite = $GLOBALS['site'];
  1788.                         if(!$currentSite){
  1789.                             if (\Pimcore\Model\Site::isSiteRequest()) {            
  1790.                                 $currentSite = \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey();
  1791.                             }
  1792.                         }                                        
  1793.                         $siteConfig =  DataObject\SiteConfig::getByPath('/Master/SiteConfig/'.$currentSite);                    
  1794.                         if($siteConfig){                        
  1795.                             $mail->addFrom($siteConfig->getFromEmail(), $siteConfig->getFromName());
  1796.                         }
  1797.                     }
  1798.                     catch(\Exception $e){
  1799.                     }*/
  1800.                     
  1801.                     $mail->send();
  1802.                 }
  1803.                 // $note->setUser($customer);
  1804.                 
  1805.                 $message =  'Document comment submitted successfully';
  1806.             } 
  1807.         }
  1808.         
  1809.         return new Response(json_encode(array("status" => "success", 'code' => '400', "message" => $message)));
  1810.      }
  1811.      /**
  1812.      * @Route("/get_file_by_versionId" , name="getDocumentByVersionId")
  1813.      *
  1814.      * @param Request $request
  1815.      * @return success or error msg
  1816.      */
  1817.     function getFileByVersionId(Request $request)
  1818.     {
  1819.         // $id = intval($request->get('versionId'));
  1820.         // $version = \Pimcore\Model\Version::getById($id);
  1821.         // if (!$version) {
  1822.         //     throw $this->createNotFoundException('Version not found');
  1823.         // }
  1824.         // $asset = $version->loadData();        
  1825.         // $assetTemplate = $this->render(
  1826.         //     'PimcoreAdminBundle:Admin/Asset:showVersion' . ucfirst($asset->getType()) . '.html.php',
  1827.         //     ['asset' => $asset]
  1828.         // );
  1829.         // $thumbnail = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/image-version-preview-" . uniqid() . ".webp";
  1830.         // $convert = \Pimcore\Image::getInstance();
  1831.         // $tempFile = $asset->getTemporaryFile();
  1832.         
  1833.         // $convert->load($tempFile);        
  1834.         // $convert->save($thumbnail, "webp");
  1835.         //$dataUri = "data:".$fileMIMEType.";base64," . base64_encode($asset->getData());
  1836.         // unlink($thumbnail);
  1837.         // unlink($tempFile);
  1838.         $id = intval($request->get('versionId'));
  1839.         $version = \Pimcore\Model\Version::getById($id);
  1840.         $dataUri = "";
  1841.         if($version){
  1842.             $asset = $version->loadData();        
  1843.             $fileMIMEType = $asset->getMimetype();        
  1844.             $dataUri = "data:".$fileMIMEType.";base64," . base64_encode($asset->getData());
  1845.         }
  1846.         return new Response(json_encode(array("status" => "success", 'code' => '200', "dataUri" => $dataUri)));
  1847.     }
  1848.     
  1849.     /**
  1850.      * @Route("/view_file_by_versionId" , name="viewDocumentByVersionId")
  1851.      *
  1852.      * @param Request $request
  1853.      * @return success or error msg
  1854.      */
  1855.     function viewFileByVersionId(Request $request)
  1856.     {
  1857.         $id = intval($request->get('versionId'));
  1858.         $version = \Pimcore\Model\Version::getById($id);
  1859.         $dataUri = "";
  1860.         if($version){
  1861.             $asset = $version->loadData();        
  1862.             $fileMIMEType = $asset->getMimetype();        
  1863.             $dataUri = "data:".$fileMIMEType.";base64," . base64_encode($asset->getData());
  1864.         }        
  1865.         return new Response(
  1866.             '<html><body><img src="'.$dataUri.'"/></body></html>'
  1867.         );
  1868.     }
  1869.     /**
  1870.      * Description:- Load view of email tempalte page
  1871.      *
  1872.      * @Route("/email-check", name="email_template_test_global")
  1873.      * @param Request $request
  1874.      *
  1875.      * @return mixed
  1876.     */
  1877.     public function emailCheckAction(Request $request, AuthenticationUtils $authenticationUtils, UserInterface $user = null)
  1878.     {
  1879.         $paramsCustomerWelcome = array('customerName'=>"TEST");        
  1880.         $mail = new \Pimcore\Mail();
  1881.         $mail->setIgnoreDebugMode(true);
  1882.         $mail->setDocument(\Pimcore\Model\Document::getByPath('/'.EMAILDOCUMENT_PATH.'/Emails/Customer/CustomerSignupWelcome'));                    
  1883.         $mail->addTo('test@yopmail.com');
  1884.         $mail->setParams($paramsCustomerWelcome);        
  1885.         $mail->setSubject("Document - Review Comments");        
  1886.         $originalEmailSubject = $mail->getSubjectRendered();
  1887.         if($GLOBALS['site'] == "3SWebsite"){
  1888.             $originalEmailSubject = str_replace("Nu Find","3s Global",$originalEmailSubject);
  1889.             $originalEmailSubject = str_replace("NuFind","3sGlobal",$originalEmailSubject);
  1890.         }
  1891.         echo $mail->getBodyHtmlRendered();
  1892.         exit;
  1893.     }
  1894.     /**
  1895.      *  Description:- Admin QR Code PDF Generate  
  1896.      *    
  1897.      * @Route("/global/generate-qrcode-pdf" , name="admin-custom-pdf");
  1898.      * @param Request $request
  1899.      * 
  1900.     */ 
  1901.     public function QRPDFGenerateAction(Request $request, Factory $ecommerceFactory)
  1902.     {
  1903.         $supplierId = $request->get("supplierId");
  1904.         $productsIds = $request->get("productsIds");        
  1905.         $perPage = $request->get("perPage");        
  1906.         $supplierPath = '/Supplier/'.$supplierId;
  1907.         $supplierObj = DataObject\SupplierCompany::getByPath($supplierPath,1);         
  1908.         if(!$supplierObj){
  1909.             echo "Unable to find supplier";
  1910.             exit;
  1911.         }
  1912.         else{                               
  1913.             $supplierProductPath= '/Product/'.$supplierId;
  1914.             $folder = \Pimcore\Model\DataObject\Service::createFolderByPath($supplierProductPath);                            
  1915.             
  1916.             $errorProducts = [];           
  1917.             $productsObjs = [];
  1918.             if (empty($supplierObj)) {
  1919.                 $errorProducts[] = "There is some issue with supplier";
  1920.             } else {
  1921.                 $prodIds = json_decode($productsIds); 
  1922.                 if($prodIds){                   
  1923.                     $prodIds    =   array_values($prodIds);                
  1924.                     
  1925.                     foreach($prodIds as $productId){          
  1926.                         try{              
  1927.                             $productObj = DataObject::getById($productId);
  1928.                             $productsObjs[] = $productObj;                        
  1929.                         }
  1930.                         catch(\Exception $e){
  1931.                             $errorProducts[] = $e->getMessage();
  1932.                         }
  1933.                     }
  1934.                 }
  1935.                 else{
  1936.                     echo "No products available for <b>".$supplierId."</b> supplier";
  1937.                     exit;
  1938.                 }
  1939.             }
  1940.         }               
  1941.         $params = [];
  1942.         $currentSite = $GLOBALS['site'] ?? null;
  1943.         if (!$currentSite && \Pimcore\Model\Site::isSiteRequest()) {
  1944.             $currentSite = \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey();
  1945.         }        
  1946.         
  1947.         $templatePath = '@Global/' . ($currentSite == "3SWebsite" ? 'default/3SWebsite' : 'product') . '/QRCode.html.twig';
  1948.         $html = $this->renderView($templatePath, ["productsObjs" => $productsObjs, "perPage" => $perPage,'isShowPrice' => true]);
  1949.         
  1950.         $fileName = 'Product-QRCode-' . $supplierId . '.pdf';
  1951.         $adapter = \Pimcore\Web2Print\Processor::getInstance();
  1952.         $adapter->setOptions("--print-media-type --page-size A4 --orientation portrait --margin-left 0.2cm --margin-right 0.15cm --margin-top 0.5cm --margin-bottom 0.5cm");
  1953.         
  1954.         // return new \Symfony\Component\HttpFoundation\Response(
  1955.         //     $adapter->getPdfFromString($html),
  1956.         //     200,
  1957.         //     array(
  1958.         //         'Content-Type' => 'application/pdf',
  1959.         //     )
  1960.         // );
  1961.         return new \Symfony\Component\HttpFoundation\Response($adapter->getPdfFromString($html, $params), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename=' . $fileName)); //direct download
  1962.     }
  1963.     /**
  1964.      *  Description:- Admin PDF HEADER Generate  
  1965.      *    
  1966.      * @Route("/global-pdf-header/{currentSite}" , name="admin-custom-pdf-header-line");
  1967.      * @param Request $request
  1968.      * 
  1969.     */ 
  1970.     public function headerPDFAction(Request $request, $currentSite="")
  1971.     {        
  1972.         $viewModel = new ViewModel();
  1973.         $headerName = $request->get('headerName');
  1974.         $viewModel->headerName = $headerName;
  1975.         $viewModel->currentSite = $currentSite;
  1976.         if($currentSite != "NuFind"){
  1977.             return $this->render('@Global/default/3SWebsite/header.html.twig',$viewModel->getAllParameters());
  1978.         }
  1979.         else{
  1980.             return $this->render('@Global/default/pdf/header.html.twig',$viewModel->getAllParameters());
  1981.         }
  1982.     }
  1983.     /**
  1984.      *  Description:- Admin PDF HEADER Generate  
  1985.      *    
  1986.      * @Route("/global-pdf-footer/{currentSite}" , name="admin-custom-pdf-footer-line");
  1987.      * @param Request $request
  1988.      * 
  1989.     */ 
  1990.     public function footerPDFAction($currentSite="")
  1991.     {        
  1992.         $viewModel = new ViewModel();
  1993.         $viewModel->currentSite = $currentSite;
  1994.         if($currentSite == "3SWebsite"){
  1995.             return $this->render('@Global/default/3SWebsite/footer.html.twig',$viewModel->getAllParameters());
  1996.         }
  1997.         else{
  1998.             return $this->render('@Global/default/pdf/footer.html.twig',$viewModel->getAllParameters());
  1999.         }
  2000.     }
  2001.     public function getOptionValues($class){
  2002.         $tempClass = $class;
  2003.         $class = ($class == "Supplier") ? "Company" : $class;
  2004.         $objectStr =  'Pimcore\\Model\\DataObject\\'.ucfirst($class).'\\Listing';        
  2005.         $object = new $objectStr(); 
  2006.         $optionName = [];                                        
  2007.         $loadObjectData = $object->load();        
  2008.         if(!empty($loadObjectData)){      
  2009.             foreach($loadObjectData as $catFieldObj){                      
  2010.                 if($tempClass == "Wishlist"){            
  2011.                     if($catFieldObj->getCustomer()){       
  2012.                         $optionName[$catFieldObj->getId()] = ($catFieldObj->getCustomer()->getEmail()." - " ?? "").$catFieldObj->getLable();
  2013.                     }
  2014.                 }
  2015.                 else if($tempClass == "Customer"){
  2016.                     $optionName[$catFieldObj->getId()] = ($catFieldObj->getEmail())." - ".$catFieldObj->getFirstname()." ".$catFieldObj->getLastname();
  2017.                 }
  2018.                 else if($tempClass == "Supplier"){
  2019.                     if (str_contains($catFieldObj->getParent()->getPath(), 'supplier')) {                    
  2020.                         $optionName[$catFieldObj->getId()] = $catFieldObj->getName();
  2021.                     }                    
  2022.                 }
  2023.                 else{
  2024.                     $optionName[$catFieldObj->getId()] = $catFieldObj->getName();
  2025.                 }
  2026.             }
  2027.         }                   
  2028.         return $optionName;
  2029.     }
  2030.     /**
  2031.      * @Route("/updateCampaign")
  2032.      *
  2033.      * @param Request $request
  2034.      * @return success or error msg
  2035.      */
  2036.      function updateCampaignFunction(Request $request)
  2037.      {         
  2038.          
  2039.         $salesCampaignId = $request->get("salesCampaignId");              
  2040.         $salesCampaignName = $request->get("salesCampaignName") ?? ""; 
  2041.         $salesCampaignSubTitle = $request->get("salesCampaignSubTitle") ?? ""; 
  2042.         $salesCampaignIsPublic = ($request->get("salesCampaignFor") == "true") ? true : false;         
  2043.         $salesCampaignAccessCode = $request->get("salesCampaignAccessCode");         
  2044.         $salesCampaignDescription = $request->get("salesCampaignDescription") ?? "";
  2045.         $salesCampaignWishlist = $request->get("salesCampaignWishlist") ?? ""; 
  2046.         $salesCampaignExclusiveSupplier = $request->get("salesCampaignExclusiveSupplier") ?? "";               
  2047.         $isActive = ($request->get("isActive") == "true") ? true : false;         
  2048.         $salesCampaignSubmitMode = $request->get("wishSubmitMode") ?? "";
  2049.         $catalogOwners = $request->get("wishCatalogOwners");
  2050.         $salesCampaignData = SalesCampaign::getById($salesCampaignId, ["force" => true]);        
  2051.         if ($salesCampaignData) {       
  2052.             
  2053.             $message = "Error";
  2054.             $code = "400";
  2055.             try{                
  2056.                 
  2057.                 //WISHLIST TO GET ALL PRODUCTS
  2058.                 if($salesCampaignWishlist){                    
  2059.                     $catalogWishlistsArray = explode(",", $salesCampaignWishlist);                                    
  2060.                     $catalogProductArray = [];
  2061.                     foreach($catalogWishlistsArray as $wishlistId){
  2062.                         $wishlistData = DataObject\Wishlist::getById($wishlistId);
  2063.                         $catalogProduct = $wishlistData->getProducts();                        
  2064.                         foreach ($catalogProduct as $ks => $vs) {
  2065.                             $catalogProductArray[$vs->getId()] = $vs;
  2066.                         }
  2067.                     }
  2068.                     $salesCampaignData->setProducts($catalogProductArray);
  2069.                     $salesCampaignData->setWishlist($catalogWishlistsArray);                      
  2070.                 }
  2071.         
  2072.                 $salesCampaignData->setIsPublic($salesCampaignIsPublic);
  2073.                 $salesCampaignData->setAccessCode($salesCampaignAccessCode);
  2074.                 $salesCampaignData->setTitle($salesCampaignName);
  2075.                 $salesCampaignData->setSubTitle($salesCampaignSubTitle);
  2076.                 $salesCampaignData->setDescription($salesCampaignDescription); 
  2077.                 
  2078.                 $exclusiveTheseSuppliers = [];
  2079.                 if($salesCampaignExclusiveSupplier){
  2080.                     $catalogExclusiveSupplierArray = explode(",", $salesCampaignExclusiveSupplier);
  2081.                     foreach($catalogExclusiveSupplierArray as $companyId){
  2082.                         $companyObject = DataObject\Company::getById($companyId);
  2083.                         $exclusiveTheseSuppliers[] = $companyObject;
  2084.                     }
  2085.                 }
  2086.                 if(count($exclusiveTheseSuppliers) > 0){
  2087.                     $salesCampaignData->setExclusiveToTheseSupplier($exclusiveTheseSuppliers);
  2088.                 }                    
  2089.                  
  2090.      
  2091.                  //  $mainImage = $request->files->get('files');                
  2092.                  //  if (!empty($mainImage)) {
  2093.                  //      for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
  2094.                  //          $path = '/_default_upload_bucket/';
  2095.                  //          $folder = Service::createFolderByPath($path);
  2096.                  //          $newAsset = new \Pimcore\Model\Asset();
  2097.                  //          $newAsset->setFilename(time() . "-" . $mainImage[$i]->getClientOriginalName());
  2098.                  //          $newAsset->setData(file_get_contents($mainImage[$i]));
  2099.                  //          $newAsset->setParentId($folder->getId());                        
  2100.                  //          if ($newAsset->save()) {
  2101.                  //              $assetArray[] = $newAsset; 
  2102.                  //              $catalogData->setImage($newAsset);                            
  2103.                  //          }
  2104.                  //      }
  2105.                  //  }
  2106.      
  2107.      
  2108.                  $bannerImage = $request->files->get('filesBanner');                
  2109.                  if (!empty($bannerImage)) {
  2110.                     $campaignBannerImages = [];
  2111.                     $bannerImages = $salesCampaignData->getBannerImage();
  2112.                     
  2113.                     if(!empty($bannerImages->getItems())){ 
  2114.                         foreach($bannerImages->getItems() as $attKey=>$attVal){ 
  2115.                             if($attVal)     
  2116.                             {   
  2117.                                 $advancedImage = new \Pimcore\Model\DataObject\Data\Hotspotimage();
  2118.                                 $advancedImage->setImage($attVal->getImage());
  2119.                                 $campaignBannerImages[] = $advancedImage;                                                          
  2120.                             }
  2121.                         }                        
  2122.                     }
  2123.                      for ($i = 0; $i < count($_FILES['filesBanner']['name']); $i++) {
  2124.                          $path = '/_default_upload_bucket/';
  2125.                          $folder = \Pimcore\Model\Asset\Service::createFolderByPath($path);
  2126.                          $newAsset = new \Pimcore\Model\Asset();
  2127.                          $newAsset->setFilename(time() . "-Banner-" . $bannerImage[$i]->getClientOriginalName());
  2128.                          $newAsset->setData(file_get_contents($bannerImage[$i]));
  2129.                          $newAsset->setParentId($folder->getId());                        
  2130.                          if ($newAsset->save()) {
  2131.                              if(!empty($newAsset)){
  2132.                                  $advancedImage = new \Pimcore\Model\DataObject\Data\Hotspotimage();
  2133.                                  $advancedImage->setImage($newAsset);
  2134.                                  $campaignBannerImages[] = $advancedImage;
  2135.                              }
  2136.                          }
  2137.                      }                     
  2138.                      $salesCampaignData->setBannerImage(new \Pimcore\Model\DataObject\Data\ImageGallery($campaignBannerImages));
  2139.                  }
  2140.                  
  2141.                  $bannerImageMobile = $request->files->get('files');                
  2142.                  if (!empty($bannerImageMobile)) {                    
  2143.                     $campaignBannerMobileImages = [];
  2144.                     $bannerImagesMobile = $salesCampaignData->getBannerImageMobile();
  2145.                     
  2146.                     if(!empty($bannerImagesMobile->getItems())){ 
  2147.                         foreach($bannerImagesMobile->getItems() as $attKey=>$attVal){ 
  2148.                             if($attVal)     
  2149.                             {   
  2150.                                 $advancedImage = new \Pimcore\Model\DataObject\Data\Hotspotimage();
  2151.                                 $advancedImage->setImage($attVal->getImage());
  2152.                                 $campaignBannerMobileImages[] = $advancedImage;                                
  2153.                             }
  2154.                         }                        
  2155.                     }
  2156.                     for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
  2157.                         $path = '/_default_upload_bucket/';
  2158.                         $folder = \Pimcore\Model\Asset\Service::createFolderByPath($path);
  2159.                         $newAsset = new \Pimcore\Model\Asset();
  2160.                         $newAsset->setFilename(time() . "-Banner-Mobile-" . $bannerImageMobile[$i]->getClientOriginalName());
  2161.                         $newAsset->setData(file_get_contents($bannerImageMobile[$i]));
  2162.                         $newAsset->setParentId($folder->getId());                        
  2163.                         if ($newAsset->save()) {
  2164.                             if(!empty($newAsset)){
  2165.                                 $advancedImage = new \Pimcore\Model\DataObject\Data\Hotspotimage();
  2166.                                 $advancedImage->setImage($newAsset);
  2167.                                 $campaignBannerMobileImages[] = $advancedImage;
  2168.                             }
  2169.                         }
  2170.                     }
  2171.                     $salesCampaignData->setBannerImageMobile(new \Pimcore\Model\DataObject\Data\ImageGallery($campaignBannerMobileImages));
  2172.                  }
  2173.                  
  2174.                 
  2175.                 if($catalogOwners){
  2176.                     $campaignExclusiveOwnersArray = explode(",", $catalogOwners);
  2177.                     foreach($campaignExclusiveOwnersArray as $customerId){
  2178.                         $customerObject = DataObject\Customer::getById($customerId);
  2179.                         $exclusiveCatalogOwners[] = $customerObject;
  2180.                     }
  2181.                 }
  2182.                 if(count($exclusiveCatalogOwners) > 0){
  2183.                     $salesCampaignData->setCampaignOwner($exclusiveCatalogOwners);
  2184.                 }
  2185.                 $salesCampaignData->setIsActive((bool)$isActive);                 
  2186.                  
  2187.                 $salesCampaignData->save();                
  2188.                 $code = "200";
  2189.                 $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;            
  2190.                 $customerId = $customer->getId();                 
  2191.                 $message = ["message"=>"Campaign updated successfully","objectId"=>$salesCampaignData->getId(), "customerId"=>$customerId];
  2192.             }
  2193.             catch(\Exception $e){                                             
  2194.                 $message = ["message"=>$e->getMessage()];
  2195.                 $code = "400";
  2196.             }            
  2197.             return new Response(json_encode(array("status" => "success", 'code' => $code, "message" => $message)));
  2198.         }
  2199.         else {
  2200.             return new Response(json_encode(array("status" => "success", 'code' => "400", "message" => ["message"=>"Error"])));
  2201.         }
  2202.      }
  2203.     /**
  2204.      * @Route("/deleteSalesCampaignMedia", name="delete-salescampaign-media")
  2205.      *
  2206.      * @param Request $request
  2207.      */
  2208.     public function deleteSalesCampaignMedia(Request $request)
  2209.     {        
  2210.         $document   = $request->get('fileData'); 
  2211.         $salesCampaignId     = $request->get('salesCampaignId');
  2212.         $fieldType     = $request->get('fieldType');        
  2213.         $error = [];
  2214.         $salesCampaignResult = [];
  2215.         $salesCampaignData = SalesCampaign::getById($salesCampaignId, ["force" => true]);        
  2216.         if ($salesCampaignData) {
  2217.             try{ 
  2218.                 if($fieldType == "bannerImage"){
  2219.                     $bannerImagesArray = [];
  2220.                     $bannerImages = $salesCampaignData->getBannerImage();
  2221.                     
  2222.                     if(!empty($bannerImages->getItems())){ 
  2223.                         foreach($bannerImages->getItems() as $attKey=>$attVal){ 
  2224.                             if($attVal)     
  2225.                             {                           
  2226.                                 if($document == $attVal->getImage()->getId()){
  2227.                                     $attVal->getImage()->delete();
  2228.                                 }else{
  2229.                                     $bannerImagesArray[] = $attVal->getImage();
  2230.                                 }
  2231.                             }
  2232.                         }
  2233.                         $salesCampaignData->setBannerImage(new \Pimcore\Model\DataObject\Data\ImageGallery($bannerImagesArray));
  2234.                     }
  2235.                 }
  2236.                 if($fieldType == "bannerImageMobile"){
  2237.                     $bannerImagesMobileArray = [];
  2238.                     $bannerImagesMobile = $salesCampaignData->getBannerImageMobile();
  2239.                     
  2240.                     if(!empty($bannerImagesMobile->getItems())){ 
  2241.                         foreach($bannerImagesMobile->getItems() as $attKey=>$attVal){    
  2242.                             if($attVal)     
  2243.                             {                   
  2244.                                 if($document == $attVal->getImage()->getId()){
  2245.                                     $attVal->getImage()->delete();
  2246.                                 }else{
  2247.                                     $bannerImagesMobileArray[] = $attVal->getImage();
  2248.                                 }
  2249.                             }
  2250.                         }
  2251.                         $salesCampaignData->setBannerImageMobile(new \Pimcore\Model\DataObject\Data\ImageGallery($bannerImagesMobileArray));
  2252.                     }
  2253.                 }
  2254.             }
  2255.             catch(\Exception $e){
  2256.                 $error[] = $e->getMessage();
  2257.             }            
  2258.         }
  2259.         else{
  2260.             $error[] = 'Sales campaign not available.';
  2261.         }
  2262.         if(count($error) > 0){
  2263.             $salesCampaignResult = ["success" => false, "msg" => implode(",", $error)];
  2264.         }else{
  2265.             $salesCampaignResult = ["success" => true, "msg" => 'Sales Campaign update successfully.'];
  2266.         }
  2267.         return $this->json($salesCampaignResult);        
  2268.     }
  2269.     
  2270.     /**
  2271.      * @Route("/download-image-frontendthumbnail", name="download_image_frontend_thumbnail")
  2272.      *
  2273.      * @param Request $request
  2274.      *
  2275.      * @return BinaryFileResponse
  2276.      */
  2277.     public function downloadImageThumbnailAction(Request $request)
  2278.     {
  2279.     
  2280.         try {
  2281.            $asset = \Pimcore\Model\Asset::getById($request->get('id'));
  2282.            if ($asset instanceof \Pimcore\Model\Asset\Image) {
  2283.            
  2284.             $originalPath = $asset->getLocalFile();
  2285.             $configJson = $request->get('config');
  2286.             
  2287.             $config = json_decode($configJson, true);
  2288.             $thumbnailConfig = new Asset\Image\Thumbnail\Config();
  2289.             $thumbnailConfig->setName('pimcore-download-' . $asset->getId() . '-' . md5($request->get('config')));
  2290.             if ($config['resize_mode'] == 'scaleByWidth') {
  2291.                 $thumbnailConfig->addItem('scaleByWidth', [
  2292.                     'width' => $config['width'],
  2293.                 ]);
  2294.             } elseif ($config['resize_mode'] == 'scaleByHeight') {
  2295.                 $thumbnailConfig->addItem('scaleByHeight', [
  2296.                     'height' => $config['height'],
  2297.                 ]);
  2298.             } else {
  2299.                 $thumbnailConfig->addItem('resize', [
  2300.                     'width' => $config['width'],
  2301.                     'height' => $config['height'],
  2302.                 ]);
  2303.             }
  2304.             $thumbnailConfig->setQuality($config['quality']);
  2305.             $thumbnailConfig->setFormat($config['format']);
  2306.             $thumbnail = $asset->getThumbnail($thumbnailConfig);
  2307.             $thumbnailFile = $thumbnail->getLocalFile();
  2308.             $downloadFilename = preg_replace(
  2309.                 '/\.' . preg_quote(File::getFileExtension($asset->getFileName())) . '$/i',
  2310.                 '.' . $thumbnail->getFileExtension(),
  2311.                 $asset->getFilename()
  2312.             );
  2313.             $thumbnailFile = str_replace('.svg', '.png', $thumbnailFile);
  2314.             $downloadUrl = $thumbnail->getFrontendPath();
  2315.             $response = new BinaryFileResponse($thumbnailFile);
  2316.             
  2317.             $response->headers->set('Content-Type', $thumbnail->getMimeType());
  2318.             $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT,$downloadFilename);
  2319.             }
  2320.             $result = ["success" => true,'downloadFile' => $thumbnailFile,'downloadFileName'=> $downloadFilename,"imageUrl" => $downloadUrl];
  2321.             return new Response(json_encode($result));
  2322.         }
  2323.         catch (\Exception $e) {
  2324.             return new Response(json_encode(["success" => false, "message" => "Thumbnail not found"]));
  2325.         }
  2326.     }
  2327.     /**
  2328.      * @Route("/download-image-popup", name="download_image_popup")
  2329.      *
  2330.      * @param Request $request
  2331.      *
  2332.      * @return BinaryFileResponse
  2333.      */
  2334.     public function downloadImagePopupAction(Request $request)
  2335.     {
  2336.         try {
  2337.            $downloadFile   = $request->get('downloadFile');
  2338.            $downloadFileName   = $request->get('downloadFileName');
  2339.            $response = new BinaryFileResponse($downloadFile);
  2340.            $response->headers->set('Content-Type', "image/png");
  2341.            $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT,$downloadFileName);
  2342.            return $response;
  2343.         }
  2344.         catch (\Exception $e) {
  2345.             $this->addFlash('error', 'Thumbnail not found');
  2346.         }
  2347.         return $this->redirect($request->headers->get('referer'));
  2348.     }
  2349.         
  2350.     
  2351. }