<?php
namespace App\Controller;
use Pimcore\Controller\FrontendController;
use Pimcore\Model\Asset\Image;
use Pimcore\Mail;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Pimcore\Model\DataObject;
use \Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
use PHPExcel_Writer_Excel2007;
use Carbon\Carbon;
use Pimcore\Model\Asset;
use ZipArchive;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use App\Model\DataObject\BrandExtension;
use PHPExcel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
#require 'PHPExcel_1.8.0/Classes/PHPExcel.php';
#require 'PHPExcel_1.8.0/Classes/PHPExcel/Writer/Excel2007.php';
// class CartController extends \Website\Controller\CartAware
/**
* @Route("/{_locale}/cart")
*/
class CartController extends CartAware
{
const COMPANY_NAME = "BeamSuntory";
private $session;
private $trance;
public function __construct(SessionInterface $session, TranslatorInterface $trance)
{
$this->session = $session;
$this->trance = $trance;
}
/**
* show top navigation
*/
public function topNavCartAction(Request $request)
{
$params = [];
$params['language'] = $request->getLocale();
$session = $request->getSession();
$authNamespace = $session->getBag('espirit');
if ($authNamespace->has('customeraccount')) {
$params['FirstName'] = $authNamespace->get('customeraccount')->getFirstName();
$params['LastName'] = $authNamespace->get('customeraccount')->getLastName();
}
$params['cart'] = $this->getCart();
return $this->render('Cart/topNavCart.html.twig',$params);
}
/**
* show product landing
*/
public function orderJsonAction(Request $request)
{
$orders = array();
$cart = $this->getCart();
if(count($cart->getItems()) == 0) {
echo json_encode($orders);
return;
}
$orderitems = array();
foreach($cart->getItems() as $item) {
$orderitems[] = array ( "id" => $item->getProduct()->getId(), "name" => $item->getProduct()->getOSName());
}
$orders["orderinfo"] = $orderitems;
//$authNamespace = new Zend_Session_Namespace('Zend_Auth');
$authNamespace = $this->get('session')->getBag('espirit');
if ($authNamespace->get('customeraccount')) {
$orders["customeraccount"] = $authNamespace->get('customeraccount');
}
$orders["downloadlink"] = $this->view->url(array('action' => 'delivery'), 'checkout');
echo @json_encode($orders);
}
/**
* @Route("/download", name="cart-download")
*
* @param Request $request
*
*/
public function downloadAction(Request $request)
{
set_time_limit(6000);
ini_set('memory_limit', '1024M');
//$this->layout()->setLayout('cart');
//$this->enableLayout();
$params = [];
$params['locale'] = strtolower($request->getLocale());
$params['hideNav'] = true;
$cart = $this->getCart();
$params['cart'] = $cart;
$defaultCountry = DataObject\AvailabilityCountry::getByPath('/availability-countries/us');
if(isset($this->country)){
$availableCountry = $this->country;
}else{
$availableCountry = $defaultCountry;
$params['country'] = $defaultCountry;
}
//if cart empty, redirect to cart list
if(count($cart->getItems()) == 0) {
//$urlHelper = \Pimcore::getContainer()->get('pimcore.templating.view_helper.pimcore_url');
//return $this->redirect($urlHelper(array('action' => 'list', 'prefix' => strtolower($this->locale)), 'cart', true));
return $this->redirectToRoute('shop-cart-detail');
}
$checkoutManager = Factory::getInstance()->getCheckoutManager( $cart );
$confirmStep = $checkoutManager->getCheckoutStep('confirm');
$checkoutManager->commitStep($confirmStep, true);
$order = $checkoutManager->commitOrder();
//$authNamespace = new Zend_Session_Namespace('Zend_Auth');
//TODO
$fileformat = 'PNG'; //We will remove this after session implementation
$session = $request->getSession();
$authNamespace = $session->getBag('espirit');
if ($authNamespace->get('photographyfileformat') == 'JPG') {
$fileformat = 'JPG';
} else {
$fileformat = 'PNG';
}
//TODO
$dim = "original"; //We will remove this after session implementation
$thumbnail = ["format" => $fileformat]; //We will remove this AFTER fix line no 131
if ($authNamespace->get('photographyfiledimension')) {
switch ($authNamespace->get('photographyfiledimension')) {
case 'eSpirits_1':
$thumbnail = ["format" => $fileformat];
$dim = "original";
break;
case 'eSpirits_2':
$thumbnail = ["width" => 750, "height" => 1500, "frame" => true, "format" => $fileformat];
$dim = "750x1500";
break;
case 'eSpirits_3':
$thumbnail = ["width" => 1000, "height" => 1000, "frame" => true, "format" => $fileformat];
$dim = "1000x1000";
break;
case 'eSpirits_4':
$thumbnail = ["width" => 1500, "height" => 1500, "frame" => true, "format" => $fileformat];
$dim = "1500x1500";
break;
case 'eSpirits_5':
$thumbnail = ["width" => 2000, "height" => 2000, "frame" => true, "format" => $fileformat];
$dim = "2000x2000";
break;
case 'eSpirits_6':
$thumbnail = ["width" => 2500, "height" => 2500, "frame" => true, "format" => $fileformat];
$dim = "2500x2500";
break;
default:
$thumbnail = ["format" => $fileformat];
$dim = "original";
break;
}
}
$order->setcountry($params['country']->getName());
//TODO
$order->setcustomer($authNamespace->get('customeraccount'));
$order->setdatafileformat($authNamespace->get('datafileformat'));
$order->setotheremail($authNamespace->get('otheremail'));
$order->setphotographyfileformat($authNamespace->get('photographyfileformat'));
//$order->setcustomer('Rohit');
$order->setdatafileformat($fileformat);
$order->setotheremail('assd.fff');
$order->setphotographyfileformat($authNamespace->get('photographyfileformat'));
$order->setphotographyfiledimension($dim);
$order->setordertype("cart");
$order->save();
//Get the order zip file
//TODO
if ($authNamespace->get('customeraccount')) {
$params['firstname'] = $authNamespace->get('customeraccount')->getFirstName();
$params['lastname'] = $authNamespace->get('customeraccount')->getLastName();
}
$params['firstname'] = '';
$params['lastname'] = '';
$excelfile = $this->create_download_file($order);
$orderdate = $order->getOrderDate();
$orderdate = Carbon::instance($orderdate);
//TODO
$downloadfilename = ((!empty($authNamespace->get('fileDownloadName'))) ? $authNamespace->get('fileDownloadName') : "Beam-Suntory_Product-Data") . "_" . $orderdate->format('Y-M-d') . "_" . $order->getId() . ".zip";
//$downloadfilename = "Beam-Suntory_Product-Data" . "_" . $orderdate->format('Y-M-d') . "_" . $order->getId() . ".zip"; //WE will remove after fix LINE NO 196
$downloadfile = "/downloads/" . $order->getId() . "/{$downloadfilename}";
//Create the file
$downloaddir = realpath("downloads");
$downloadpath = "";
if (!file_exists($downloaddir . "/" . $order->getId())) {
mkdir($downloaddir . "/" . $order->getId(), 0777, true);
}
$downloadpath = $downloaddir . "/" . $order->getId() . "/{$downloadfilename}";
if (!empty($downloadpath)) {
$files_to_zip = array();
foreach ($order->getItems() as $item) {
$product = $item->getProduct();
//Get all the lifesize
//TODO
//Get all the bottle-size photos
$sizeVariants = $product->getSizeVariants($this->country);
if ($sizeVariants) {
foreach($sizeVariants as $variant) {
//if ($variant->getBottleSize() == '750 m') {
$countries = $variant->getCountryAvailabilityList();
$continue = 0;
foreach ($countries as $country) {
if ($country->getObject()->getId() == $this->country->getId() && $country->geteSpiritsEnable() == 1) {
$continue = 1;
break;
}
}
if ($continue == 0) {
continue;
}
if ($variant->getBottlePhoto()) {
$files_to_zip[] = $variant->getBottlePhoto();
}
$additionalPhotos = $variant->getAdditionalPhotos();
if(!empty($additionalPhotos))
{
foreach($additionalPhotos as $a)
{
$files_to_zip[] = $a['AdditionalPhoto']->getData();
}
}
}
//}
}
/* Excluding Videos for now
$videos = $product->getVideoList();
if(!empty($videos))
{
foreach($videos as $v) //
{
$files_to_zip[] = sprintf("/website/var/assets%s", $v->getFullPath());
}
}
*/
}
for($i=0; $i<count($files_to_zip); $i++)
{
{
$asset = Asset::getByPath($files_to_zip[$i]);
$tn = $asset->getThumbnail($thumbnail, false)->getLocalFile();
$files_to_zip[$i] = $tn; // .form-group div -> clear: both; label for picks float: left
}
}
$files_to_zip[] = $excelfile;
//if true, good; if false, zip creation failed
if (count($files_to_zip) > 0) {
$result = $this->create_zip($files_to_zip,$downloadpath,true);
}
}
$params['downloadurl'] = $downloadfile;
$params['downloadfilename'] = $downloadfilename;
//Send the Email
//$params = array();
$params["order"] = $order;
$params["customer"] = $order->getCustomer();
$params["ordernumber"] = $order->getOrdernumber();
$size = "0. 0 KB";
if (file_exists($_SERVER['DOCUMENT_ROOT'] . $downloadfile)) {
$size = $this->filesize_formatted($_SERVER['DOCUMENT_ROOT'] . $downloadfile);
}
$params["filesize_formatted"] = $size;
$mail = new Mail(array("document" => "/espirits/" . strtolower($this->locale) . "/emails/download-confirmation", "params" => $params));
if($order->getCustomer()) {
$mail->setIgnoreDebugMode(true);
//$mail->setDefaultFrom("contact@beamsuntory.com","eSpirits Portal");
$mail->subject("Saudi Aramco Document Data Download | " . $order->getOrderDate()->format('YYYY-MM-dd') . " | " . $order->getId());
$mail->addTo($order->getCustomer()->getEmail());
//TODO
if ($authNamespace->get('otheremail')) {
$toemails = explode(",", $authNamespace->get('otheremail'));
foreach ($toemails as $toemail) {
if (!empty( $toemail )) $mail->addTo( $toemail );
}
}
#fix the email sending
//****$mail->send();
} else {
//TODO We will be uncomment
//\Logger::err("No Customer found!");
}
// init
$params["order"] = \Pimcore\Model\DataObject\OnlineShopOrder::getById( $order->getId() );
//need to revisit
//**$itemKeyUniversal = \Pimcore\Bundle\EcommerceFrameworkBundle\CheckoutManager\CheckoutManager::TRACK_ECOMMERCE_UNIVERSAL . "_" . $order->getOrdernumber();
$itemKeyUniversal = 'checkout_trackecommerce_universal' . "_" . $order->getOrdernumber();
$environment = Factory::getInstance()->getEnvironment();
$codeUniversal = $environment->getCustomItem($itemKeyUniversal);
if(!empty($codeUniversal)) {
$params["gacodeUniversal"] = $codeUniversal;
$environment->removeCustomItem($itemKeyUniversal);
$environment->save();
}
return $this->render('Cart/download.html.twig', $params);
}
/**
* @Route("/list", name="shop-cart-detail", methods={"GET"})
*
* @param Request $request
* @param BreadcrumbHelperService $breadcrumbHelperService
* @param Factory $ecommerceFactory
*
*/
public function listAction(Request $request, Factory $ecommerceFactory): Response
{
// init view
//$this->layout()->setLayout('cart');
//$this->enableLayout();
$params = [];
$params['hideNav'] = true;
$params['locale'] = strtolower($request->getLocale());
$params['params'] = $request->request->all();
$params['preview'] = $request->get('pimcore_preview',null);
$defaultCountry = DataObject\AvailabilityCountry::getByPath('/availability-countries/us');
if(isset($this->country)){
$availableCountry = $this->country;
}else{
$availableCountry = $defaultCountry;
$params['country'] = $defaultCountry;
}
$cart = $this->getCart();
// sort by item count asc
//Todo item
// $cart->sortItems(function (\Pimcore\Bundle\EcommerceFrameworkBundle\CartManager\ICartItem $a, \Pimcore\Bundle\EcommerceFrameworkBundle\CartManager\ICartItem $b) {
// return $a->getCount() > $b->getCount();
// });
$cart = $this->getCart();
if ($request->getMethod() == Request::METHOD_POST) {
$items = $request->get('items');
foreach ($items as $itemKey => $quantity) {
if ($cart->getItemCount() > 99) {
break;
}
$product = BrandExtension::getById($itemKey);
if ($product instanceof CheckoutableInterface) {
$cart->updateItem($itemKey, $product, $quantity, true);
}
}
$cart->save();
$trackingManager = $ecommerceFactory->getTrackingManager();
$trackingManager->trackCartUpdate($cart);
}
$params['cart'] = $cart;
//$breadcrumbHelperService->enrichCartPage();
//$params = array_merge($request->request->all(), $request->query->all());
if ($cart->isEmpty()) {
return $this->render('Cart/list.html.twig', $params);
} else {
return $this->render('Cart/list.html.twig', $params);
}
}
/**
* @Route("/add-to-cart", name="shop-add-to-cart")
*
* @param Request $request
* @param Factory $ecommerceFactory
*
* @throws \Exception
*/
public function addAction(Request $request)
{
// add item to cart
if(($id = $request->get('item')))
{
$product = DataObject\BrandExtension::getById( $id );
$prefix = $request->get('prefix');
/* @var \Website\DefaultProduct $product */
$qty = (int)$request->get('qty', 1);
if($product)
{
$cart = $this->getCart();
$cart->addItem( $product, $qty);
$cart->save();
}
//$urlHelper = \Pimcore::getKernel()->getContainer()->get('pimcore.templating.view_helper.pimcore_url');
//$url = $urlHelper(array('action' => 'list'), 'cart');
//return $this->redirect( $url );
// $url = $this->generateUrl('shop-cart-detail');
//return $this->redirectToRoute('shop-cart-detail');
$url = $this->generateUrl('shop-cart-detail');
return $this->redirect($url);
} else {
throw new \Exception("no item given to add to cart");
}
}
/**
* @Route("/remove-from-cart", name="shop-remove-from-cart")
*/
public function removeAction(Request $request)
{
// remove item from cart
if(($id = $request->get('item')))
{
$cart = $this->getCart();
$cart->removeItem( $id );
$cart->save();
//$urlHelper = \Pimcore::getContainer()->get('pimcore.templating.view_helper.pimcore_url');
//return $this->redirect( $urlHelper(array('action' => 'list'), 'cart') );
return $this->redirectToRoute('shop-cart-detail');
} else {
throw new \Exception("no item given to remove from cart");
}
}
/**
* @Route("/update", name="cart-update", methods={"GET"})
*
* @param Request $request
* @param Factory $ecommerceFactory
*
* @throws \Exception
*/
public function updateAction(Request $request)
{
if($request->get("qty")) {
$cart = $this->getCart();
foreach($request->get("qty") as $key => $qty) {
$product = Pimcore\Model\Object\Product::getById($key);
if($product) {
$cart->updateItem($key, $product, intval($qty), true);
$cart->save();
}
}
}
$url = $this->view->url(array('action' => 'list'), 'cart');
return $this->redirect( $url );
}
/**
* Adds a voucher token to cart, sets error messages and
* redirects to list action.
*/
public function addVoucherAction(Request $request)
{
$cart = $this->getCart();
$voucherError = "";
if ($token = strip_tags($request->get('voucherToken'))) {
try {
$success = $cart->addVoucherToken($token);
if(!$success) {
$voucherError = $this->view->t('cart.msg-error-token-couldnt-be-applied');
}
} catch (\Pimcore\Bundle\EcommerceFrameworkBundle\Exception\VoucherServiceException $e) {
$voucherError = $this->view->t('cart.msg-error.' . $e->getCode());
}
} else {
$voucherError = $this->view->t('cart.msg-error-token-missing');
}
$params = ["action" => "list", "prefix" => $this->locale];
if($voucherError) {
$params["voucherError"] = $voucherError;
$params["voucherToken"] = $token;
}
$url = $this->view->url($params, 'cart', true);
return $this->redirect($url);
}
/**
* Remove a voucher token from cart, sets error messages and
* redirects to list action.
*/
public function releaseVoucherAction(Request $request)
{
$cart = $this->getCart();
$voucherError = "";
if ($code = $request->get('voucherToken')) {
try {
$cart->removeVoucherToken($code);
} catch (\Pimcore\Bundle\EcommerceFrameworkBundle\Exception\VoucherServiceException $e){
$voucherError = $this->view->t('cart.msg-error.' . $e->getCode());
}
} else {
$voucherError = $this->view->t('cart.msg-error-token-missing');
}
$url = $this->view->url(array('action' => 'list', 'voucherError' => $voucherError), 'cart');
return $this->redirect($url);
}
private function filesize_formatted($path)
{
$size = filesize($path);
$units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$power = $size > 0 ? floor(log($size, 1024)) : 0;
return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
}
/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination)) {
$overwrite = true;
} else {
$overwrite = false;
}
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$new_filename = substr($file,strrpos($file,'/') + 1);
if (preg_match('#xlsx#', $file) === 0) {
$new_filename = "assets/" . $new_filename;
//$new_filename = "product-media/bottle-photos/" . $new_filename;
}
if(is_dir($file))
{
continue;
}
$zip->addFile($file, $new_filename);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
function create_download_file($order) {
//$objPHPExcel = new PHPExcel();
$objPHPExcel = new Spreadsheet();
// Set properties
$pr = $objPHPExcel->getProperties();
$ttl = $this->trance->trans("espirits.export.title");
//$pr->setCreator(self::COMPANY_NAME);
$pr->setLastModifiedBy(self::COMPANY_NAME);
$pr->setTitle($ttl);
$pr->setSubject($ttl);
$pr->setDescription($ttl);
// Write product info sheet.
$objPHPExcel->setActiveSheetIndex(0);
$sht = $objPHPExcel->getActiveSheet();
$sht->setTitle($this->trance->trans("espirits.export.Product Info"));
$headers = array("ObjectType", "Brand", "BrandExtensionName", "BrandExtensionNameTrademark", "BottleSize", "BrandExtensionDiscontinued", "ABV", "ShortDescription", "FullDescription", "Aging", "BottlePhoto", "LifestylePhotoList", "OriginCountry", "OriginRegion", "AlcoholType", "FlavoringType", "PricingSegment", "WhyBuy1", "WhyBuy2", "WhyBuy3", "WhyBuy4", "WhyBuy5", "WhyBuy6", "WhyBuy7", "WhyBuy8", "Keywords1", "Keywords2", "Keywords3", "Keywords4", "Keywords5", "Keywords6", "Keywords7", "Keywords8", "Keywords9", "Keywords10", "Keywords11", "Keywords12", "Keywords13", "Keywords14", "Keywords15", "Keywords16", "Keywords17", "Keywords18", "Keywords19", "Keywords20", "Keywords21", "Keywords22", "Keywords23", "Keywords24", "Keywords25", "Keywords26", "Keywords27", "Keywords28", "Keywords29", "Keywords30", "GTIN", "Material", "Height", "Width", "Depth", "Weight", "BSIID", "modificationDate", "creationDate");
$this->country = DataObject\AvailabilityCountry::getByPath('/availability-countries/us');
//TODO Replace default country by lofined user by country
if($this->country != "DE")
{
$headers = array_merge(array_slice($headers, 0, 7), array("Proof"), array_slice($headers, 7));
}
$this->writeHeaders($sht, $headers);
$counter = 1;
foreach ($order->getItems() as $item) {
$counter++;
$product = $item->getProduct();
if ($this->locale == "de")
{
$this->create_excel_row_de($objPHPExcel, $product, "BrandExtension", $counter);
} else
{
$this->create_excel_row($objPHPExcel, $product, "BrandExtension", $counter);
}
$sizeVariants = $product->getSizeVariants();
if ($sizeVariants) {
foreach($sizeVariants as $variant) {
$countries = $variant->getCountryAvailabilityList();
$continue = 0;
foreach ($countries as $country) {
if ($country->getObjectId() == $this->country->getId() && $country->geteSpiritsEnable() == 1) {
$continue = 1;
break;
}
}
if ($continue == 0) {
continue;
}
$counter++;
if ($this->country->getName() == "DE") {
$this->create_excel_row_de($objPHPExcel, $variant, "BottleVariant", $counter);
} else {
$this->create_excel_row($objPHPExcel, $variant, "BottleVariant", $counter);
}
}
}
}
$objPHPExcel->createSheet(1);
$objPHPExcel->setActiveSheetIndex(1);
$sht = $objPHPExcel->getActiveSheet();
$sht->setTitle($this->trance->trans("espirits.export.Recipes"));
$this->writeHeaders($sht, array("Recipe Name", "Brand Extension Name", "Ingredients", "Preparation", "Recipe Image Path"));
$ctr = 2;
foreach($order->getItems() as $item)
{
$product = $item->getProduct();
}
$objPHPExcel->setActiveSheetIndex(0);
// Set properties
$objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xlsx');
$objWriter->save($_SERVER['DOCUMENT_ROOT'] . "/downloads/excel/Products_Download_" . $order->getId() . ".xlsx");
return $_SERVER['DOCUMENT_ROOT'] . "/downloads/excel/Products_Download_" . $order->getId() . ".xlsx";
}
public function writeHeaders($sht, $hdrs)
{
$kv = "A";
foreach($hdrs as $h)
{
$sht->SetCellValue(sprintf("%s1", $kv), $this->trance->trans(sprintf("espirits.export.%s", $h)));
$kv++;
}
}
public function removeHTML($s)
{
$rt = str_replace(array("<p>", "</p>"), array("", "\r\n"), $s);
$rt = preg_replace("/<\/?.*?>/", "", $rt);
$rt = html_entity_decode($rt, ENT_COMPAT | ENT_HTML401, "UTF-8");
return $rt;
}
function create_excel_row($objPHPExcel, $product, $producttype, $counter)
{
$brandname = "";
$brandextname = "";
$brandextensionnametrademark = "";
$bottlesize = "";
$BrandExtensionDiscontinued = "";
$proof = "";
$abv = "";
$shortdesc = "";
$fulldesc = "";
$region = "";
$country = "";
$alcoholtype = "";
$aging = "";
$lifestylephotos = "";
$bottlephotos = "";
$bottleGTIN = "";
$bottleBottleMaterial = "";
$bottleBottleHeight = "";
$bottleBottleWidth = "";
$bottleBottleDepth = "";
$bottleBottleWeight = "";
$flv = "";
$seg = "";
if ($producttype == "BrandExtension") {
$brandextname = $product->getName();
$brandextensionnametrademark = $product->getName();
$brand = $product->getBrand();
if ($brand) $brandname = $brand[0]->getObject()->getBrandName();
$fulldesc = $product->getContent();
//Country Origin
$categories = $product->getCategories();
if ($categories) foreach ($categories as $category) {
break;
}
if ($category) $alcoholtype = $category->getAlcoholType();
}
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $counter, $this->trance->trans("espirits.export." . $producttype));
$objPHPExcel->getActiveSheet()->SetCellValue('B' . $counter, iconv("UTF-8", "ISO-8859-1//IGNORE", $brandname));
$objPHPExcel->getActiveSheet()->SetCellValue('C' . $counter, iconv("UTF-8", "ISO-8859-1//IGNORE", $brandextname));
$objPHPExcel->getActiveSheet()->SetCellValue('D' . $counter, iconv("UTF-8", "ISO-8859-1//IGNORE", $brandextensionnametrademark));
// Existing code for keywords 1 and 2
$objPHPExcel->getActiveSheet()->SetCellValue('E' . $counter, $product->getId());
//$create_date = new Zend_Date($product->getcreationDate());
$create_date = Carbon::createFromTimestamp($product->getcreationDate());
$create_date = $create_date->format("YYYY/MM/dd");
//$modify_date = new Zend_Date($product->getmodificationDate());
$modify_date = Carbon::createFromTimestamp($product->getmodificationDate());
$modify_date = $modify_date->format("YYYY/MM/dd");
$objPHPExcel->getActiveSheet()->SetCellValue('F' . $counter, $modify_date);
$objPHPExcel->getActiveSheet()->SetCellValue('G' . $counter, $create_date);
}
function create_excel_row_de($objPHPExcel, $product, $producttype, $counter)
{
$brandname = "";
$brandextname = "";
$brandextensionnametrademark = "";
$bottlesize = "";
$BrandExtensionDiscontinued = "";
$proof = "";
$abv = "";
$shortdesc = "";
$fulldesc = "";
$region = "";
$country = "";
$alcoholtype = "";
$aging = "";
$lifestylephotos = "";
$bottlephotos = "";
$bottleGTIN = "";
$bottleBottleMaterial = "";
$bottleBottleHeight = "";
$bottleBottleWidth = "";
$bottleBottleDepth = "";
$bottleBottleWeight = "";
if ($producttype == "BrandExtension") {
$brandextname = $product->getBrandExtensionName();
$brandextensionnametrademark = $product->getBrandExtensionNameTrademark();
$brand = $product->getBrand();
if ($brand) $brandname = $brand[0]->getObject()->getBrandName();
if ($product->getBrandExtensionDiscontinued()) $BrandExtensionDiscontinued = "1";
$proof = $product->getProof();
$abv = $product->getABV();
$shortdesc = $product->getShortDescription();
$fulldesc = $product->getFullDescription();
//Country Origin
$region = $product->getOriginRegion();
$country = $product->getOriginCountry();
$countrydic = $product->getClass()->getFieldDefinition("OriginCountry")->getOptions();
foreach ($countrydic as $countrydicitem) {
if ($countrydicitem['value'] == $country) {
$country = $countrydicitem['key'];
break;
}
}
//Aging
$aging = $product->getAging();
//Pricing Segment
$segs = $product->PricingSegment;
if ($segs) foreach ($segs as $seg) {
break;
}
if ($seg) $seg = $seg->getObject();
if ($seg) $seg = $seg->getPricingSegment();
//Flavoring Type
$flvs = $product->FlavoringType;
if ($flvs) foreach ($flvs as $flv) {
break;
}
if ($flv) $flv = $flv->getObject();
if ($flv) $flv = $flv->getFlavoringType();
$categories = $product->getCategories();
if ($categories) foreach ($categories as $category) {
break;
}
if ($category) $alcoholtype = $category->getAlcoholType();
//Get all the lifesize
if ($product->getLifestylePhotoList()) {
foreach ($product->getLifestylePhotoList()->getItems() as $item) {
if ($item && $item->getPhotoLifestyle() && $item->getPhotoLifestyle()->getFullPath()) {
if (!empty($lifestylephotos)) $lifestylephotos .= ",";
$lifestylephotos .= $item->getPhotoLifestyle()->getFullPath();
}
}
}
} else {
$bottlesize = $product->getBottleSize();
//Get all the bottle-size photos
$bottlephoto = $product->getBottlePhoto();
$bottlephotos = "";
if ($bottlephoto) $bottlephotos = $bottlephoto->getFilename();
$additionalPhotos = $product->getAdditionalPhotos();
if (!empty($additionalPhotos)) {
foreach ($additionalPhotos as $a) {
$bottlephotos .= "," . $a['AdditionalPhoto']->getData()->getFilename();
}
}
$bottleGTIN = $product->getGTIN();
$bottleBottleMaterial = $product->getBottleMaterial();
$bottleBottleHeight = $product->getBottleHeight();
$bottleBottleWidth = $product->getBottleWidth();
$bottleBottleDepth = $product->getBottleDepth();
$bottleBottleWeight = $product->getBottleWeight();
}
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $counter, $this->get('translator')->trans("espirits.export." . $producttype));
$objPHPExcel->getActiveSheet()->SetCellValue('B' . $counter, $brandname);
$objPHPExcel->getActiveSheet()->SetCellValue('C' . $counter, $brandextname);
$objPHPExcel->getActiveSheet()->SetCellValue('D' . $counter, $brandextensionnametrademark);
$objPHPExcel->getActiveSheet()->SetCellValue('E' . $counter, $bottlesize);
$objPHPExcel->getActiveSheet()->SetCellValue('F' . $counter, $BrandExtensionDiscontinued);
$objPHPExcel->getActiveSheet()->SetCellValue('G' . $counter, $abv);
$objPHPExcel->getActiveSheet()->SetCellValue('H' . $counter, $shortdesc);
$objPHPExcel->getActiveSheet()->SetCellValue('I' . $counter, $fulldesc);
$objPHPExcel->getActiveSheet()->SetCellValue('J' . $counter, $aging);
$objPHPExcel->getActiveSheet()->SetCellValue('K' . $counter, $bottlephotos);
$objPHPExcel->getActiveSheet()->SetCellValue('L' . $counter, $lifestylephotos);
$objPHPExcel->getActiveSheet()->SetCellValue('M' . $counter, $country);
$objPHPExcel->getActiveSheet()->SetCellValue('N' . $counter, $region);
$objPHPExcel->getActiveSheet()->SetCellValue('O' . $counter, $alcoholtype);
$objPHPExcel->getActiveSheet()->SetCellValue('P' . $counter, $flv);
$objPHPExcel->getActiveSheet()->SetCellValue('Q' . $counter, $seg);
$buyAlpha = array("R", "S", "T", "U", "V", "W", "X", "Y");
for ($i = 1; $i <= 8; $i++) {
if ($producttype == "BrandExtension") {
$whybuy = "getWhyBuy" . $i;
$whybuys = $product->$whybuy();
if (is_null($whybuys)) {
$whybuys = "";
}
$objPHPExcel->getActiveSheet()->SetCellValue($buyAlpha[$i - 1] . $counter, $whybuys);
} else {
$objPHPExcel->getActiveSheet()->SetCellValue($buyAlpha[$i - 1] . $counter, "");
}
}
$keyAlpha = array("Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI");
for ($i = 1; $i <= 10; $i++) {
if ($producttype == "BrandExtension") {
$keyword = "Keywords" . $i;
$kwords = $product->localizedfields->items[$this->locale->toString()][$keyword];
if (is_null($kwords)) {
$keywords = "";
}
$objPHPExcel->getActiveSheet()->SetCellValue($keyAlpha[$i - 1] . $counter, $kwords);
} else {
$objPHPExcel->getActiveSheet()->SetCellValue($keyAlpha[$i - 1] . $counter, "");
}
}
$objPHPExcel->getActiveSheet()->SetCellValue('AJ' . $counter, $bottleGTIN);
$objPHPExcel->getActiveSheet()->SetCellValue('AK' . $counter, $bottleBottleMaterial);
$objPHPExcel->getActiveSheet()->SetCellValue('AL' . $counter, $bottleBottleHeight);
$objPHPExcel->getActiveSheet()->SetCellValue('AM' . $counter, $bottleBottleWidth);
$objPHPExcel->getActiveSheet()->SetCellValue('AN' . $counter, $bottleBottleDepth);
$objPHPExcel->getActiveSheet()->SetCellValue('AO' . $counter, $bottleBottleWeight);
$objPHPExcel->getActiveSheet()->SetCellValue('AP' . $counter, $product->getId());
//$create_date = new Zend_Date($product->getcreationDate());
$create_date = Carbon::createFromTimestamp($product->getcreationDate());
$create_date = $create_date->format("YYYY/MM/dd");
//$modify_date = new Zend_Date($product->getmodificationDate());
$modify_date = Carbon::createFromTimestamp($product->getmodificationDate());
$modify_date = $modify_date->format("YYYY/MM/dd");
$objPHPExcel->getActiveSheet()->SetCellValue('AQ' . $counter, $modify_date);
$objPHPExcel->getActiveSheet()->SetCellValue('AR' . $counter, $create_date);
}
}