<?php

namespace Benhauer\Salesmanago\Model\Events;

use \Magento\Framework\UrlInterface;
use \Benhauer\Salesmanago\Model\AbstractModel as SalesmanagoAbstractModel;

class Purchase extends SalesmanagoAbstractModel
{
    /**
     * @param $order
     * @param $quoteFactory
     * @return array
     */
    public function getPurchseByOrder($order, $quoteFactory)
    {
        try {
            $dateTime = $this->objDate->date();

            $prods = [
                'ids' => [],
                'names' => [],
                'qty' => [],
                'sku' => []
            ];

            $quote = $quoteFactory
                ->create()
                ->load($order->getQuoteId());

            $quoteItems = $quote->getAllVisibleItems();

            foreach ($quoteItems as $item) {
                if ($item->getPrice() > 0
                    && $item->getPrice() != null
                ) {
                    array_push($prods['ids'], $item->getProductId());
                    array_push($prods['names'], $item->getName());
                    array_push($prods['qty'], $item->getQty());
                    array_push($prods['sku'], $item->getSku());
                }
            }

            $purchaseContent = [
                'date' => $dateTime->format('c'),
                'description' => $order->getPayment()->getMethod(),
                'products' => implode(",", $prods['ids']),
                'location' => $this->model->getSMStoreId(UrlInterface::URL_TYPE_WEB),
                'value' => $order->getGrandTotal(),
                'detail1' => implode(",", $prods['names']),
                'detail2' => implode("/", $prods['qty']),
                'detail3' => implode(",", $prods['sku']),
                'detail4' => $order->getBaseCurrencyCode(),
                'externalId' => $order->getEntityId(),
                'shopDomain' => $this->store->getBaseUrl(UrlInterface::URL_TYPE_WEB)
            ];

            return $purchaseContent;
        } catch (\Exception $e) {
            $this->logger->critical($e->getMessage());
        }
    }
}