/**
  * Automation new wishlist program.
  *
  * @param array $wishlist
  *
  * @return $this
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function registerWishlist($wishlist)
 {
     try {
         $emailWishlist = $this->wishlistFactory->create();
         $customer = $this->customerFactory->create();
         //if wishlist exist not to save again
         if (!$emailWishlist->getWishlist($wishlist['wishlist_id'])) {
             $customer->load($wishlist['customer_id']);
             $email = $customer->getEmail();
             $wishlistId = $wishlist['wishlist_id'];
             $websiteId = $customer->getWebsiteId();
             $emailWishlist->setWishlistId($wishlistId)->setCustomerId($wishlist['customer_id'])->setStoreId($customer->getStoreId())->save();
             $store = $this->storeManager->getStore($customer->getStoreId());
             $storeName = $store->getName();
             //if api is not enabled
             if (!$this->helper->isEnabled($websiteId)) {
                 return $this;
             }
             $programId = $this->helper->getWebsiteConfig('connector_automation/visitor_automation/wishlist_automation', $websiteId);
             //wishlist program mapped
             if ($programId) {
                 $automation = $this->automationFactory->create();
                 //save automation type
                 $automation->setEmail($email)->setAutomationType(\Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_TYPE_NEW_WISHLIST)->setEnrolmentStatus(\Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_STATUS_PENDING)->setTypeId($wishlistId)->setWebsiteId($websiteId)->setStoreName($storeName)->setProgramId($programId);
                 $automation->save();
             }
         }
     } catch (\Exception $e) {
         $this->helper->error((string) $e, []);
     }
 }
 /**
  * Initial sync the transactional data.
  *
  * @return array
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function sync()
 {
     $response = ['success' => true, 'message' => 'Done.'];
     // Initialise a return hash containing results of our sync attempt
     $this->_searchAccounts();
     foreach ($this->accounts as $account) {
         $orders = $account->getOrders();
         $orderIds = $account->getOrderIds();
         $ordersForSingleSync = $account->getOrdersForSingleSync();
         $orderIdsForSingleSync = $account->getOrderIdsForSingleSync();
         //@codingStandardsIgnoreStart
         $numOrdersForSingleSync = count($ordersForSingleSync);
         $website = $account->getWebsites();
         $numOrders = count($orders);
         //@codingStandardsIgnoreEnd
         $this->countOrders += $numOrders;
         $this->countOrders += $numOrdersForSingleSync;
         //send transactional for any number of orders set
         if ($numOrders) {
             $this->helper->log('--------- Order sync ---------- : ' . $numOrders);
             //queue order into importer
             $this->helper->error('orders', $orders);
             try {
                 $this->importerFactory->create()->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_ORDERS, $orders, \Dotdigitalgroup\Email\Model\Importer::MODE_BULK, $website[0]);
             } catch (\Exception $e) {
                 $this->helper->debug((string) $e, []);
             }
             $this->_setImported($orderIds);
             $this->helper->log('----------end order sync----------');
         }
         if ($numOrdersForSingleSync) {
             $error = false;
             foreach ($ordersForSingleSync as $order) {
                 $this->helper->log('--------- register Order sync in single with importer ---------- : ');
                 //register in queue with importer
                 $this->importerFactory->create()->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_ORDERS, $order, \Dotdigitalgroup\Email\Model\Importer::MODE_SINGLE, $website[0]);
                 $this->helper->log('----------end order sync in single----------');
             }
             //if no error then set imported
             if (!$error) {
                 $this->_setImported($orderIdsForSingleSync, true);
             }
         }
         unset($this->accounts[$account->getApiUsername()]);
     }
     /**
      * Add guest to contacts table.
      */
     if (!empty($this->guests)) {
         $this->contactFactory->create()->insert($this->guests);
     }
     if ($this->countOrders) {
         $response['message'] = 'Orders updated ' . $this->countOrders;
     }
     return $response;
 }
 /**
  * Execute method.
  */
 public function execute()
 {
     $code = $this->getRequest()->getParam('code', false);
     $userId = $this->getRequest()->getParam('state');
     //load admin user
     $adminUser = $this->adminUser->create()->load($userId);
     //app code and admin user must be present
     if ($code && $adminUser->getId()) {
         $clientId = $this->scopeConfig->getValue(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_CLIENT_ID);
         $clientSecret = $this->scopeConfig->getValue(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_CLIENT_SECRET_ID);
         //callback uri if not set custom
         $redirectUri = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB, true);
         $redirectUri .= 'connector/email/callback';
         $data = 'client_id=' . $clientId . '&client_secret=' . $clientSecret . '&redirect_uri=' . $redirectUri . '&grant_type=authorization_code' . '&code=' . $code;
         //callback url
         $url = $this->config->getTokenUrl();
         //@codingStandardsIgnoreStart
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
         curl_setopt($ch, CURLOPT_POST, count($data));
         curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
         curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
         $response = json_decode(curl_exec($ch));
         if ($response === false) {
             $this->helper->error('Error Number: ' . curl_errno($ch), []);
         }
         if (isset($response->error)) {
             $this->helper->error('OAUTH failed ' . $response->error, []);
         } elseif (isset($response->refresh_token)) {
             //save the refresh token to the admin user
             $adminUser->setRefreshToken($response->refresh_token)->save();
         }
         //@codingStandardsIgnoreEnd
     }
     //redirect to automation index page
     $this->_redirect($this->adminHelper->getUrl('dotdigitalgroup_email/studio'));
 }