<?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\Sales\Model\Order;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory as OrderCollectionFactory;


/**
 * @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 OrderRepositoryInterface
     */
    private $orderRepository;
    /**
     * @var OrderCollectionFactory
     */
    private $orderCollectionFactory;
    /**
     * @var Order
     */
    protected $order;

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

    /**
     * @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;
    }

    /**
     * @param $email
     * @return array
     * @throws \Magento\Framework\Exception\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();
    }
}
