<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Model\ResourceModel;

use FiloBlu\Refilo\Api\Data\OrderMappingInterface;
use FiloBlu\Refilo\Api\OrderMappingRepositoryInterface;
use Magento\Framework\App\ResourceConnection;

/**
 * @class OrderMappingRepository
 * @package FiloBlu\Refilo\Model\ResourceModel
 */
class OrderMappingRepository implements OrderMappingRepositoryInterface
{
    const TABLE = 'filoblu_order_mapping';

    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

    /**
     * @param ResourceConnection $resourceConnection
     */
    public function __construct(
        ResourceConnection $resourceConnection
    ) {
        $this->resourceConnection = $resourceConnection;
    }

    /**
     * @param \FiloBlu\Refilo\Api\Data\OrderMappingInterface $orderMapping
     * @return \FiloBlu\Refilo\Api\Data\OrderMappingInterface
     */
    public function save(\FiloBlu\Refilo\Api\Data\OrderMappingInterface $orderMapping)
    {
        $connection = $this->resourceConnection->getConnection();
        $table = $connection->getTableName(self::TABLE);

        $connection->insert(
            $table,
            [
                OrderMappingInterface::CUSTOMER_ID => $orderMapping->getCustomerId(),
                OrderMappingInterface::ORDER_ID => $orderMapping->getOrderId(),
                OrderMappingInterface::ORDER_STORE_ID => $orderMapping->getOrderStoreId()
            ]
        );

        $orderMapping->setId($connection->lastInsertId($table));

        return $orderMapping;
    }

    /**
     * @param $customerId
     * @param $orderId
     * @return mixed
     */
    public function get($customerId, $orderId)
    {
        $connection = $this->resourceConnection->getConnection();
        $table = $connection->getTableName(self::TABLE);

        $select = $connection->select()
            ->from($table)
            ->where('customer_id = ?', $customerId)
            ->where('order_id = ?', $orderId);

        return $connection->fetchRow($select);
    }

    /**
     * @param $customerId
     * @param array $storeIds
     * @return array|mixed
     */
    public function getByCustomerId($customerId, array $storeIds = [])
    {
        $connection = $this->resourceConnection->getConnection();
        $table = $connection->getTableName(self::TABLE);

        $select = $connection->select()
            ->from($table, [OrderMappingInterface::ORDER_ID])
            ->where('customer_id = ?', $customerId);

        if (!empty($storeIds)) {
            $select->where('order_store_id IN (?)', $storeIds);
        }

        return $connection->fetchCol($select);
    }
}
