/**
  * @param $address
  * @param $customer
  * @return int
  * @throws ShopgateLibraryException
  */
 public function createAddress(ShopgateAddress $address, $customer)
 {
     /** @var AddressCore | Address $addressModel */
     $addressItem = new Address();
     $addressItem->id_customer = $customer->id;
     $addressItem->lastname = $address->getLastName();
     $addressItem->firstname = $address->getFirstName();
     if ($address->getCompany()) {
         $addressItem->company = $address->getCompany();
     }
     $addressItem->address1 = $address->getStreet1();
     if ($address->getStreet2()) {
         $addressItem->address2 = $address->getStreet2();
     }
     $addressItem->city = $address->getCity();
     $addressItem->postcode = $address->getZipcode();
     if (!Validate::isLanguageIsoCode($address->getCountry())) {
         $customer->delete();
         throw new ShopgateLibraryException(ShopgateLibraryException::REGISTER_FAILED_TO_ADD_USER, 'invalid country code: ' . $address->getCountry(), true);
     }
     $addressItem->id_country = Country::getByIso($address->getCountry());
     /**
      * prepare states
      */
     $stateParts = explode('-', $address->getState());
     if (count($stateParts) == 2) {
         $address->setState($stateParts[1]);
     }
     if ($address->getState() && !Validate::isStateIsoCode($address->getState())) {
         $customer->delete();
         throw new ShopgateLibraryException(ShopgateLibraryException::REGISTER_FAILED_TO_ADD_USER, 'invalid state code: ' . $address->getState(), true);
     } else {
         $addressItem->id_state = State::getIdByIso($address->getState());
     }
     $addressItem->alias = $address->getIsDeliveryAddress() ? $this->getModule()->l('Default delivery address') : $this->getModule()->l('Default');
     $addressItem->alias = $address->getIsInvoiceAddress() ? $this->getModule()->l('Default invoice address') : $this->getModule()->l('Default');
     $addressItem->phone = $address->getPhone();
     $addressItem->phone_mobile = $address->getMobile();
     $shopgateCustomFieldsHelper = new ShopgateCustomFieldsHelper();
     $shopgateCustomFieldsHelper->saveCustomFields($addressItem, $address->getCustomFields());
     $validateMessage = $addressItem->validateFields(false, true);
     if ($validateMessage !== true) {
         $customer->delete();
         throw new ShopgateLibraryException(ShopgateLibraryException::REGISTER_FAILED_TO_ADD_USER, $validateMessage, true);
     }
     $addressItem->save();
     return $addressItem->id;
 }
 /**
  * @param ShopgateOrder $order
  *
  * @return array
  * @throws PrestaShopException
  * @throws ShopgateLibraryException
  */
 public function addOrder(ShopgateOrder $order)
 {
     /**
      * check exits shopgate order
      */
     if (ShopgateOrderPrestashop::loadByOrderNumber($order->getOrderNumber())->status == 1) {
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DUPLICATE_ORDER, sprintf('external_order_id: %s', $order->getOrderNumber()), true);
     }
     /** @var CarrierCore $sgCarrier */
     $sgCarrier = new Carrier(Configuration::get('SG_CARRIER_ID'));
     if (version_compare(_PS_VERSION_, '1.5.0', '<') && empty($sgCarrier->name)) {
         $sgCarrier->name = 'shopgate_tmp_carrier';
     }
     if ($order->getShippingType() != ShopgateShipping::DEFAULT_PLUGIN_API_KEY) {
         if ($order->getShippingInfos()->getAmount() > 0) {
             if (version_compare(_PS_VERSION_, '1.5.0', '<')) {
                 ShopgateModObjectModel::updateShippingPrice(pSQL($order->getShippingInfos()->getAmount()));
             } else {
                 $data = array('price' => pSQL($order->getShippingInfos()->getAmount()));
                 $where = 'a.id_carrier = ' . (int) Configuration::get('SG_CARRIER_ID');
                 ObjectModel::updateMultishopTable('Delivery', $data, $where);
             }
             $sgCarrier->is_free = 0;
         } else {
             $sgCarrier->is_free = 1;
         }
     }
     $sgCarrier->update();
     $customerModel = new ShopgateItemsCustomerImportJson($this->getPlugin());
     $paymentModel = new ShopgatePayment($this->getModule());
     $shippingModel = new ShopgateShipping($this->getModule());
     /**
      * read / check customer
      */
     if (!($customerId = Customer::customerExists($order->getMail(), true, false))) {
         /**
          * prepare customer
          */
         $shopgateCustomerItem = new ShopgateCustomer();
         $shopgateCustomerItem->setLastName($order->getInvoiceAddress()->getLastName());
         $shopgateCustomerItem->setFirstName($order->getInvoiceAddress()->getFirstName());
         $shopgateCustomerItem->setGender($order->getInvoiceAddress()->getGender());
         $shopgateCustomerItem->setBirthday($order->getInvoiceAddress()->getBirthday());
         $shopgateCustomerItem->setNewsletterSubscription(Configuration::get('SG_SUBSCRIBE_NEWSLETTER') ? true : false);
         $customerId = $customerModel->registerCustomer($order->getMail(), md5(_COOKIE_KEY_ . time()), $shopgateCustomerItem);
     }
     /** @var CustomerCore $customer */
     $customer = new Customer($customerId);
     /**
      * prepare cart
      */
     if (!$order->getDeliveryAddress()->getPhone()) {
         $order->getDeliveryAddress()->setPhone($order->getPhone());
     }
     if (!$order->getInvoiceAddress()->getPhone()) {
         $order->getInvoiceAddress()->setPhone($order->getPhone());
     }
     $this->getCart()->id_address_delivery = $customerModel->createAddress($order->getDeliveryAddress(), $customer);
     $this->getCart()->id_address_invoice = $customerModel->createAddress($order->getInvoiceAddress(), $customer);
     $this->getCart()->id_customer = $customerId;
     // id_guest is a connection to a ps_guest entry which includes screen width etc.
     // is_guest field only exists in Prestashop 1.4.1.0 and higher
     if (version_compare(_PS_VERSION_, '1.4.1.0', '>=')) {
         $this->getCart()->id_guest = $customer->is_guest;
     }
     $this->getCart()->secure_key = $customer->secure_key;
     $this->getCart()->id_carrier = $shippingModel->getCarrierIdByApiOrder($order);
     $shopgateCustomFieldsHelper = new ShopgateCustomFieldsHelper();
     $shopgateCustomFieldsHelper->saveCustomFields($this->getCart(), $order->getCustomFields());
     $this->getCart()->add();
     /**
      * add cart items
      */
     $canCreateOrder = true;
     $errorMessages = array();
     foreach ($order->getItems() as $item) {
         list($productId, $attributeId) = ShopgateHelper::getProductIdentifiers($item);
         if ($productId == 0) {
             continue;
         }
         $updateCart = $this->getCart()->updateQty($item->getQuantity(), $productId, $attributeId, false, 'up', $this->getCart()->id_address_delivery);
         if ($updateCart !== true) {
             $canCreateOrder = false;
             $errorMessages[] = array('product_id' => $productId, 'attribute_id' => $attributeId, 'quantity' => $item->getQuantity(), 'result' => $updateCart, 'reason' => $updateCart == -1 ? 'minimum quantity not reached' : '');
         }
     }
     /**
      * coupons
      */
     foreach ($order->getExternalCoupons() as $coupon) {
         /** @var CartRuleCore $cartRule */
         $cartRule = new CartRule(CartRule::getIdByCode($coupon->getCode()));
         if (Validate::isLoadedObject($cartRule)) {
             $this->getCart()->addCartRule($cartRule->id);
             $this->getCart()->save();
         }
     }
     if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
         /**
          * this field is not available in version 1.4.x.x
          * set delivery option
          */
         $delivery_option = array($this->getCart()->id_address_delivery => $shippingModel->getCarrierIdByApiOrder($order) . ',');
         $this->getCart()->setDeliveryOption($delivery_option);
     }
     /**
      * store shopgate order
      */
     $shopgateOrderItem = new ShopgateOrderPrestashop();
     $shopgateOrderItem->fillFromOrder($this->getCart(), $order, $this->getPlugin()->getShopgateConfig()->getShopNumber());
     if (version_compare(_PS_VERSION_, '1.6.0.0', '<')) {
         $shopgateOrderItem->add();
     }
     /**
      * create order
      */
     if ($canCreateOrder) {
         /**
          * get first item from order stats
          */
         $this->getCart()->save();
         $idOrderState = reset($paymentModel->getOrderStateId($order));
         $validateOder = $this->getModule()->validateOrder($this->getCart()->id, $idOrderState, $this->getCart()->getOrderTotal(true, defined('Cart::BOTH') ? Cart::BOTH : 3), $paymentModel->getPaymentTitleByKey($order->getPaymentMethod()), null, array(), null, false, $this->getCart()->secure_key);
         if (version_compare(_PS_VERSION_, '1.5.0.0', '<') && (int) $this->getModule()->currentOrder > 0 && $order->getShippingType() != ShopgateShipping::DEFAULT_PLUGIN_API_KEY && $order->getShippingInfos()->getAmount() > 0) {
             ShopgateLogger::log('PS < 1.5.0.0: update shipping and payment cost', ShopgateLogger::LOGTYPE_DEBUG);
             // in versions below 1.5.0.0 the shipping and payment costs must be updated after the order was imported
             /** @var OrderCore $updateShopgateOrder */
             $updateShopgateOrder = new Order($this->getModule()->currentOrder);
             $updateShopgateOrder->total_shipping = $order->getAmountShipping() + $order->getAmountShopPayment();
             $updateShopgateOrder->total_paid += $order->getAmountShipping() + $order->getAmountShopPayment();
             $updateShopgateOrder->total_paid_real += $order->getAmountShipping() + $order->getAmountShopPayment();
             $updateShopgateOrder->update();
         }
         /**
          * update shopgate order
          */
         if ($validateOder) {
             $shopgateOrderItem->id_order = $this->getModule()->currentOrder;
             $shopgateOrderItem->status = 1;
             $shopgateOrderItem->save();
             return array('external_order_id' => $shopgateOrderItem->id_order, 'external_order_number' => $shopgateOrderItem->id_order);
         }
     }
     $shopgateOrderItem->delete();
     throw new ShopgateLibraryException(ShopgateLibraryException::UNKNOWN_ERROR_CODE, 'Unable to create order:' . print_r($errorMessages, true), true);
 }