<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Helper;

use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilderFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory as OrderCollectionFactory;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\Website;

/**
 * @class OrderMapping
 * @package FiloBlu\Refilo\Helper
 */
class OrderMappingHelper
{
    const XML_PATH_ORDER_DASHBOARD = 'refilo_sales/in_store_order_dashboard/enabled';

    /**
     * @var StoreRepositoryInterface
     */
    private $storeRepository;
    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;
    /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepository;
    /**
     * @var SearchCriteriaBuilderFactory
     */
    private $searchCriteriaBuilderFactory;
    /**
     * @var OrderCollectionFactory
     */
    private $orderCollectionFactory;
    /**
     * @var Order
     */
    protected $order;
    /**
     * @var WebsiteRepositoryInterface
     */
    private $websiteRepository;

    /**
     * @param ScopeConfigInterface $scopeConfig
     * @param StoreRepositoryInterface $storeRepository
     * @param CustomerRepositoryInterface $customerRepository
     * @param SearchCriteriaBuilderFactory $searchCriteriaBuilderFactory
     * @param OrderCollectionFactory $orderCollectionFactory
     * @param WebsiteRepositoryInterface $websiteRepository
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        StoreRepositoryInterface $storeRepository,
        CustomerRepositoryInterface $customerRepository,
        SearchCriteriaBuilderFactory $searchCriteriaBuilderFactory,
        OrderCollectionFactory $orderCollectionFactory,
        WebsiteRepositoryInterface $websiteRepository
    ) {
        $this->storeRepository = $storeRepository;
        $this->scopeConfig = $scopeConfig;
        $this->customerRepository = $customerRepository;
        $this->searchCriteriaBuilderFactory = $searchCriteriaBuilderFactory;
        $this->orderCollectionFactory = $orderCollectionFactory;
        $this->websiteRepository = $websiteRepository;
    }

    /**
     * @return array
     */
    public function getEnabledStore(): array
    {
        $stores = $this->storeRepository->getList();

        $enabledStore = [];
        foreach ($stores as $store) {
            $enabled = $this->scopeConfig->getValue(
                self::XML_PATH_ORDER_DASHBOARD,
                ScopeInterface::SCOPE_STORE,
                $store->getCode()
            );

            if ($enabled === '1' && $store->getIsActive()) {
                $enabledStore[$store->getId()] = $store->getCode();
            }
        }

        return $enabledStore;
    }

    /**
     * Add stores in same website
     * @param array $storeIds
     * @return array
     */
    public function addStoreIds(array $storeIds): array
    {
        if (empty($storeIds)) {
            return [];
        }

        $storeIds = array_map('\intval', $storeIds);

        /** @var Website $website */
        foreach ($this->websiteRepository->getList() as $website) {
            $ids = $website->getStoreIds();
            if (array_intersect($ids, $storeIds) === []) {
                continue;
            }

            foreach ($ids as $id) {
                $storeIds[] = (int)$id;
            }
        }

        return array_unique($storeIds);
    }
    /**
     * @param $email
     * @return array
     * @throws LocalizedException
     */
    public function getCustomerIdListByEmail($email): array
    {
        $searchCriteria = $this->searchCriteriaBuilderFactory->create()
            ->addFilter('email', $email)
            ->create();

        $customers = $this->customerRepository->getList($searchCriteria);

        $ids = [];
        foreach ($customers->getItems() as $customer) {
            $ids[$customer->getStoreId()] = $customer->getId();
        }

        return $ids;
    }

    /**
     * @param string|null $orderId
     * @param string|null $protectCode
     * @return bool
     */
    public function checkIfOrderIsValid($orderId, $protectCode) : bool
    {
        if (!$orderId || !$protectCode) {
            return false;
        }

        $collection = $this->orderCollectionFactory->create()
            ->addFieldToFilter('entity_id', $orderId)
            ->addFieldToFilter('protect_code', $protectCode)
            ->setPageSize(1);

         return $collection->getSize() > 0;
    }

    /**
     * TODO: bug
     * @return float|string|null
     */
    public function getOrderCustomerEmail()
    {
        if (empty($this->order)) {
            return null;
        }

        return $this->order->getCustomerEmail();
    }

    /**
     * Retrieve order entity ids for a given customer.
     *
     * @param int|string $customerId
     * @return int[] Array of order entity ids
     */
    public function getCustomerOrderIds($customerId): array
    {
        return $this->orderCollectionFactory->create()
            ->addFieldToFilter('customer_id', $customerId)->addFieldToSelect(['entity_id'])
            ->getAllIds();
    }
}
