<?php

namespace Benhauer\Salesmanago\Model;

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

class Export extends SalesmanagoAbstractModel
{
    const
        CUSTOMER_COLLECTION_TABLE = 'customer_entity',
        SUBSCRIBER_COLLECTION_TABLE = 'newsletter_subscriber';

    private $contactOptStatus;
    private $exportTags;

    /**
     * @param object $collection Customerse or Subscribers
     * @param object $subscriber to check if customer is subscribed
     * @return array $tags
     */
    public function prepareContactsToExport($collection, $subscriber)
    {
        $contacts = [];
        $isCustomer = ($collection->getMainTable() == self::CUSTOMER_COLLECTION_TABLE) ? true : false;

        foreach ($collection as $customer) {
            $customerEmail = $customer->getEmail();

            $cSubscribed = $subscriber->loadByEmail($customerEmail);

             /* "if" below - fix magento load subscriber bug - in magento version 2.3.2:
             * when try to load subscriber by customer email or customer id - was returned different email of suscriber*/
            if($customerEmail != $cSubscribed->getEmail()){
                $isSubscribed = false;
            } else {
                $isSubscribed = boolval($cSubscribed->isSubscribed());
            }

            if (!empty($customerEmail)) {

                $tags = $this->prepareTags($isSubscribed, $isCustomer);

                $smContact = [
                    'contact' => [
                        'email' => $customer->getEmail(),
                        'name'  => $customer->getName(),
                        'externalId' => $customer->getId(),
                    ],
                    'birthday' => (!empty($customer->getDob()))
                        ? date('Ymd', strtotime($customer->getDob()))
                        : '',
                    'tags' => $tags,
                    'removeTags' => '',
                ];

                if (isset($this->contactOptStatus)) {
                    $smContact = array_merge($smContact, $this->contactOptStatus);
                } else {
                    $smContact = array_merge($smContact,
                        [
                            'forceOptIn' => $isSubscribed,
                            'forceOptOut' => !$isSubscribed,
                            'forcePhoneOptIn' => $isSubscribed,
                            'forcePhoneOptOut' => !$isSubscribed
                        ]
                    );
                }

                if ($addr = $customer->getDefaultBillingAddress()) {
                    $smContact['contact'] = array_merge(
                        $smContact['contact'],
                        [
                            'phone'   => $addr->getTelephone(),
                            'fax'     => $addr->getFax(),
                            'company' => $addr->getCompany(),
                            'address'    => [
                                'streetAddress' => implode(',', $addr->getStreet()),
                                'zipCode'       => $addr->getPostcode(),
                                'city'          => $addr->getCity(),
                                'country'       => $addr->getCountry()
                            ],
                        ]
                    );

                    if ($addr->getRegion()) {
                        $smContact = array_merge($smContact,
                            [
                                'province' => $addr->getRegion()
                            ]
                        );
                    }
                }

                $contacts[] = $this->filterData($smContact);
            }
        }
        return $contacts;
    }

    public function prepareOrdersToExport($orders)
    {
        $extEvents = [];

        foreach ($orders as $order) {
            $products = $order->getAllVisibleItems();

            $prodData = [
                'ids' => [],
                'names' => [],
                'skus' => [],
                'qtys' => []
            ];

            foreach ($products as $product) {
                $prodData['ids'][]   = $product->getProductId();
                $prodData['names'][] = $product->getName();
                $prodData['skus'][]  = $product->getSku();
                $prodData['qtys'][]  = round($product->getQtyOrdered());
            }

            $status = (
                $order->getData('status') == 'complete'
                || $order->getData('status') == 'closed'
                || $order->getData('status') == 'pending'
            ) ? "PURCHASE" : "CART";

            $store = $this->storeManager->getStore();
            $storeUrl = $store->getBaseUrl(UrlInterface::URL_TYPE_WEB);

            if ($status != "CART") {
                $extEvents[] = [
                    'email' => $order->getCustomerEmail(),
                    'contactEvent' => [
                        'date' => strtotime($order->getData('created_at')) * 1000,
                        'description' => $order->getPayment()->getMethod(),
                        'products' => (isset($prodData['ids'])) ? implode(",", $prodData['ids']) : '',
                        'location' => $this->getSMStoreId(),
                        'value' => $order->getGrandTotal(),
                        'contactExtEventType' => $status,
                        'detail1' => (isset($prodData['names'])) ? implode(",", $prodData['names']) : '',
                        'detail2' => (isset($prodData['qtys'])) ? implode("/", $prodData['qtys']) : '',
                        'detail3' => (isset($prodData['skus'])) ? implode("/", $prodData['skus']) : '',
                        'detail4' => $order->getBaseCurrencyCode(),
                        'externalId' => $order->getRealOrderId(),
                        'shopDomain' => $storeUrl
                    ]
                ];
            }
        }

        return $extEvents;
    }

    public function setContactOptStatus($param)
    {
        switch ($param) {
            case "optIn":
                $this->contactOptStatus = [
                    'forceOptIn' => true,
                    'forceOptOut' => false,
                    'forcePhoneOptIn' => true,
                    'forcePhoneOptOut' => false
                ];
                break;
            case "optOut":
                $this->contactOptStatus = [
                    'forceOptIn' => false,
                    'forceOptOut' => true,
                    'forcePhoneOptIn' => false,
                    'forcePhoneOptOut' => true
                ];
                break;
        }
    }

    public function setExportTags($param)
    {
        $this->exportTags = strpos($param, ',')
            ? explode(',', $param)
            : [$param];
    }

    /**
     * @param boolean $isSubscribed
     * @param boolean $isCustomer
     * @return array $tags
     */
    public function prepareTags($isSubscribed = false, $isCustomer = false)
    {
        $tags = $isSubscribed
            ? explode(",", $this->getTags(self::T_NEWS))
            : [];
        $tags = $isCustomer
            ? array_merge($tags, explode(",", $this->getTags(self::T_REGISTER)))
            : $tags;
        $tags = isset($this->exportTags)
            ? array_merge($tags, $this->exportTags)
            : $tags;

        return $tags;
    }
}
