/**
     * Constructor method
     *
     * @param integer $orderID Shopware order id
     * @throws Exception
     */
    public function __construct($orderID)
    {
        $OrderResource = Shopware\Components\Api\Manager::getResource('Order');
        try {
            $this->order = $OrderResource->getOne($orderID);
        } catch (\Shopware\Components\Api\Exception\NotFoundException $E) {
            throw new PlentymarketsExportEntityException('The incoming payment of the order with the id »' . $orderID . '« could not be booked (order not found)', 4110);
        }
        $Result = Shopware()->Db()->query('
			SELECT
					*
				FROM plenty_order
				WHERE shopwareId = ?
		', array($orderID));
        $plentyOrder = $Result->fetchObject();
        if (!is_object($plentyOrder) || (int) $plentyOrder->plentyOrderId <= 0) {
            throw new PlentymarketsExportEntityException('The incoming payment of the order with the number »' . $this->order['number'] . '« could not be booked (order was not yet exported)', 4120);
        }
        if (!is_null($plentyOrder->plentyOrderPaidTimestamp)) {
            throw new PlentymarketsExportEntityException('The incoming payment of the order with the number »' . $this->order['number'] . '« could not be booked (has already been exported)', 4130);
        }
        $this->plentyOrder = $plentyOrder;
    }
 /**
  * Returns the Variant resource
  *
  * @return \Shopware\Components\Api\Resource\Variant
  */
 protected static function getVariantApi()
 {
     if (is_null(self::$VariantApi)) {
         self::$VariantApi = Shopware\Components\Api\Manager::getResource('Variant');
     }
     return self::$VariantApi;
 }
    /**
     * Either deletes or deactivates all shopware item that
     * are not associated with the store id configured.
     */
    protected function pruneItems()
    {
        // Create a temporary table
        Shopware()->Db()->exec('
			CREATE TEMPORARY TABLE IF NOT EXISTS plenty_cleanup_item
				(itemId INT UNSIGNED, INDEX (itemId))
				ENGINE = MEMORY;
		');
        // Get the data from plentymarkets (for every mapped shop)
        $shopIds = Shopware()->Db()->fetchAll('
			SELECT plentyID FROM plenty_mapping_shop
		');
        foreach ($shopIds as $shopId) {
            $Request_GetItemsByStoreID = new PlentySoapRequest_GetItemsByStoreID();
            $Request_GetItemsByStoreID->Page = 0;
            $Request_GetItemsByStoreID->StoreID = $shopId['plentyID'];
            do {
                // Do the request
                $Response_GetItemsByStoreID = PlentymarketsSoapClient::getInstance()->GetItemsByStoreID($Request_GetItemsByStoreID);
                // Call failed
                if (is_null($Response_GetItemsByStoreID) || !property_exists($Response_GetItemsByStoreID, 'Items')) {
                    // Log
                    PlentymarketsLogger::getInstance()->error('Cleanup:Item', 'Aborting. GetItemsByStoreID apparently failed');
                    // Delete the temporary table
                    Shopware()->Db()->exec('
						DROP TEMPORARY TABLE plenty_cleanup_item
					');
                    return;
                }
                $itemIds = array();
                foreach ($Response_GetItemsByStoreID->Items->item as $ItemByStoreID) {
                    $itemIds[] = $ItemByStoreID->intValue;
                }
                if (empty($itemIds)) {
                    break;
                }
                // Build the sql statement
                $itemsIdsSql = implode(', ', array_map(function ($itemId) {
                    return sprintf('(%u)', $itemId);
                }, $itemIds));
                // Fill the table
                Shopware()->Db()->exec('
					INSERT IGNORE INTO plenty_cleanup_item VALUES ' . $itemsIdsSql . '
				');
            } while (++$Request_GetItemsByStoreID->Page < $Response_GetItemsByStoreID->Pages);
        }
        // Get the action
        $actionId = PlentymarketsConfig::getInstance()->getItemCleanupActionID(self::ITEM_ACTION_DEACTIVATE);
        $where = '';
        if ($actionId == self::ITEM_ACTION_DEACTIVATE) {
            $where = ' AND s_articles.active = 1';
        }
        // Get all items, that are neither in the cleanup nor the mapping table
        $Result = Shopware()->Db()->fetchAll('
			SELECT
					id
				FROM s_articles
				WHERE
					id NOT IN (
						SELECT pmi.shopwareID
							FROM plenty_cleanup_item pci
							LEFT JOIN plenty_mapping_item pmi ON pmi.plentyID = pci.itemId
							WHERE pmi.shopwareID IS NOT NULL

					) ' . $where . '
		');
        // Handle the items
        foreach ($Result as $item) {
            /** @var Shopware\Models\Article\Article $Item */
            $Item = Shopware()->Models()->find('Shopware\\Models\\Article\\Article', $item['id']);
            if (!$Item) {
                continue;
            }
            if ($actionId == self::ITEM_ACTION_DEACTIVATE) {
                if ($Item->getActive()) {
                    $Item->setActive(false);
                }
                foreach ($Item->getDetails() as $Detail) {
                    /** @var Shopware\Models\Article\Detail $Detail */
                    if ($Detail->getActive()) {
                        $Detail->setActive(false);
                        if ($Detail->getAdditionalText()) {
                            PlentymarketsLogger::getInstance()->message('Cleanup:Item', 'The item variant »' . $Item->getName() . ' (' . $Detail->getAdditionalText() . ')« with the number »' . $Detail->getNumber() . '« will be deactivated');
                        } else {
                            PlentymarketsLogger::getInstance()->message('Cleanup:Item', 'The item »' . $Item->getName() . ' with the number »' . $Detail->getNumber() . '« will be deactivated');
                        }
                    }
                }
                try {
                    Shopware()->Models()->persist($Item);
                    Shopware()->Models()->flush();
                } catch (Exception $E) {
                    PlentymarketsLogger::getInstance()->error('Cleanup:Item', 'The item »' . $Item->getName() . '« could not be completely deactivated (' . $E->getMessage() . ')', 1420);
                }
            } else {
                if ($actionId == self::ITEM_ACTION_DELETE) {
                    try {
                        $Resource = Shopware\Components\Api\Manager::getResource('Article');
                        $Resource->delete($Item->getId());
                        PlentymarketsLogger::getInstance()->message('Cleanup:Item', 'The item »' . $Item->getName() . '« with the number »' . $Item->getMainDetail()->getNumber() . '« has been deleted');
                    } catch (Exception $E) {
                        PlentymarketsLogger::getInstance()->error('Cleanup:Item', 'The item »' . $Item->getName() . '« with the number »' . $Item->getMainDetail()->getNumber() . '« could not be deleted (' . $E->getMessage() . ')', 1420);
                    }
                }
            }
        }
        // Delete the temporary table
        Shopware()->Db()->exec('
			DROP TEMPORARY TABLE plenty_cleanup_item
		');
    }
    /**
     * @description Set the translation for the object for the language shops
     * @param string $type
     * @param int $objectId
     * @param int $languageShopId
     * @param array $data
     */
    public static function setShopwareTranslation($type, $objectId, $languageShopId, $data)
    {
        $sw4_sql = null;
        $sw5_sql = null;
        try {
            $sql = 'SHOW FULL COLUMNS FROM `s_core_translations`;';
            $Result = Shopware()->Db()->query($sql);
            $lastColumn = array_pop($Result->fetchAll());
            if ($lastColumn['Field'] == 'dirty') {
                // create sql query for saving the translation for shopware version 5
                // !!! objectlanguage = language shopId
                // !!! objectkey = object Id (e.g. article Id)
                $sw5_sql = 'INSERT INTO `s_core_translations` (
				`objecttype`, `objectdata`, `objectkey`, `objectlanguage`,  `dirty`
				) VALUES (
				?, ?, ?, ?,?
				) ON DUPLICATE KEY UPDATE `objectdata`=VALUES(`objectdata`);
				';
            } elseif ($lastColumn['Field'] == 'objectlanguage') {
                // create sql query for saving the translation for shopware version 4
                // !!! objectkey = object Id (e.g. article Id)
                $sw4_sql = 'INSERT INTO `s_core_translations` (
				`objecttype`, `objectdata`, `objectkey`, `objectlanguage`
				) VALUES (
				?, ?, ?, ?
				) ON DUPLICATE KEY UPDATE `objectdata`=VALUES(`objectdata`);
				';
            }
        } catch (Exception $e) {
            PlentymarketsLogger::getInstance()->error('Sync:Translation', 'The translation could not be imported » shopware version » (' . $e->getMessage() . ')', 3020);
        }
        try {
            if (isset($sw5_sql)) {
                // try saving the translation for shopware version 5
                Shopware()->Db()->query($sw5_sql, array($type, serialize($data), $objectId, $languageShopId, 1));
            } elseif (isset($sw4_sql)) {
                // try saving the translation for shopware version 4
                Shopware()->Db()->query($sw4_sql, array($type, serialize($data), $objectId, $languageShopId));
            } else {
                PlentymarketsLogger::getInstance()->error('Sync:Translation', 'The translation could not be imported » shopware version', 3020);
                return;
            }
            Shopware\Components\Api\Manager::getResource('Translation')->flush();
        } catch (Shopware\Components\Api\Exception\OrmException $E) {
            PlentymarketsLogger::getInstance()->error('Sync:Translation', 'The translation type » ' . $type . ' «  for shopId » ' . $languageShopId . '« has been imported with errors (' . $E->getMessage() . ')', 3020);
        }
    }
    /**
     * @description Set the translation for the object for the language shops
     * @param string $type
     * @param int $objectId
     * @param int $languageShopId
     * @param array $data
     */
    public static function setShopwareTranslation($type, $objectId, $languageShopId, $data)
    {
        try {
            // !!! objectlanguage = language shopId
            // !!! objectkey = object Id (e.g. article Id)
            $sql = 'INSERT INTO `s_core_translations` (
				`objecttype`, `objectdata`, `objectkey`, `objectlanguage`,  `dirty`
				) VALUES (
				?, ?, ?, ?,?
				) ON DUPLICATE KEY UPDATE `objectdata`=VALUES(`objectdata`);
				';
            Shopware()->Db()->query($sql, array($type, serialize($data), $objectId, $languageShopId, 1));
            Shopware\Components\Api\Manager::getResource('Translation')->flush();
        } catch (Shopware\Components\Api\Exception\OrmException $E) {
            PlentymarketsLogger::getInstance()->error('Sync:Translation', 'The translation type » ' . $type . ' «  for shopId » ' . $languageShopId . '« has been imported with errors (' . $E->getMessage() . ')', 3020);
        }
    }
 /**
  * I am the constructor
  *
  * @param PlentySoapObject_ItemCategoryTreeNode|PlentySoapObject_ItemCategory $categoryNode
  * @param integer $storeId
  * @throws Exception
  */
 public function __construct($categoryNode, $storeId, $categoryNodeLang = 'de')
 {
     $category = array();
     if (property_exists($categoryNode, 'ItemCategoryPath')) {
         $categoryPath = explode(';', $categoryNode->ItemCategoryPath);
         $categoryPathNames = explode(';', $categoryNode->ItemCategoryPathNames);
     } else {
         if (property_exists($categoryNode, 'CategoryPath')) {
             $categoryPath = explode(';', $categoryNode->CategoryPath);
             $categoryPathNames = explode(';', $categoryNode->CategoryPathNames);
         } else {
             throw new Exception();
         }
     }
     foreach ($categoryPath as $n => $categoryId) {
         if ($categoryId == 0) {
             break;
         }
         $category[] = array('branchId' => $categoryId, 'name' => $categoryPathNames[$n]);
     }
     $this->plentyCategoryBranch = $category;
     $this->storeId = $storeId;
     $this->shopId = PlentymarketsMappingController::getShopByPlentyID($storeId);
     $this->categoryNodeLang = $categoryNodeLang;
     // get the main language of the shop set it temp
     $mainLang = array_values(PlentymarketsTranslation::getShopMainLanguage($this->shopId));
     $this->shopLang = PlentymarketsTranslation::getPlentyLocaleFormat($mainLang[0]['locale']);
     if (is_null(self::$CategoryRepository)) {
         self::$CategoryRepository = Shopware()->Models()->getRepository('Shopware\\Models\\Category\\Category');
     }
     if (is_null(self::$CategoryApi)) {
         self::$CategoryApi = Shopware\Components\Api\Manager::getResource('Category');
     }
 }
 /**
  * I am the constructor
  *
  * @param PlentySoapObject_ItemCategoryTreeNode|PlentySoapObject_ItemCategory $categoryNode
  * @param integer $storeId
  * @throws Exception
  */
 public function __construct($categoryNode, $storeId)
 {
     $category = array();
     if (property_exists($categoryNode, 'ItemCategoryPath')) {
         $categoryPath = explode(';', $categoryNode->ItemCategoryPath);
         $categoryPathNames = explode(';', $categoryNode->ItemCategoryPathNames);
     } else {
         if (property_exists($categoryNode, 'CategoryPath')) {
             $categoryPath = explode(';', $categoryNode->CategoryPath);
             $categoryPathNames = explode(';', $categoryNode->CategoryPathNames);
         } else {
             throw new Exception();
         }
     }
     foreach ($categoryPath as $n => $categoryId) {
         if ($categoryId == 0) {
             break;
         }
         $category[] = array('branchId' => $categoryId, 'name' => $categoryPathNames[$n]);
     }
     $this->plentyCategoryBranch = $category;
     $this->storeId = $storeId;
     $this->shopId = PlentymarketsMappingController::getShopByPlentyID($storeId);
     if (is_null(self::$CategoryRepository)) {
         self::$CategoryRepository = Shopware()->Models()->getRepository('Shopware\\Models\\Category\\Category');
     }
     if (is_null(self::$CategoryApi)) {
         self::$CategoryApi = Shopware\Components\Api\Manager::getResource('Category');
     }
 }