<?php
/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 24/02/20
 * Time: 13.38
 */

namespace FiloBlu\Rma\Model;

use FiloBlu\Rma\Api\RmaExtensionAttributesRepositoryInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory as OrderCollectionFactory;
use Psr\Log\LoggerInterface;


class SyncChangeSizeOrder
{
    /**
     * @var OrderCollectionFactory
     */
    protected $orderCollectionFactory;

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

    /**
     * @var LoggerInterface
     */
    private $logger;


    /**
     * SyncChangeSizeOrder constructor.
     * @param OrderCollectionFactory $orderCollection
     * @param ResourceConnection $resourceConnection
     * @param LoggerInterface $logger
     */
    public function __construct(
        OrderCollectionFactory $orderCollection,
        ResourceConnection $resourceConnection,
        LoggerInterface $logger
    ) {
        $this->orderCollectionFactory = $orderCollection;
        $this->resourceConnection = $resourceConnection;
        $this->logger = $logger;
    }

    /**
     * @return void
     */
    public function deleteExistingsValues()
    {
        $connection = $this->resourceConnection->getConnection();
        $table = $connection->getTableName(RmaExtensionAttributesRepositoryInterface::TABLE_NAME);
        $connection->query("DELETE FROM $table WHERE 1");
    }

    /**
     * @param array $ids
     * @return array
     */
    public function insertChangeSizeOrderBulk(array $ids)
    {
        $connection = $this->resourceConnection->getConnection();
        $table = $connection->getTableName(RmaExtensionAttributesRepositoryInterface::TABLE_NAME);
        $sql = "INSERT INTO $table (`rma_item_id`,`order_id`) VALUES";
        $sqlParts = '';

        foreach ($ids as $id) {
            $sqlParts .= "({$id['rma_item_id']},{$id['order_id']})";
            if (next($ids)) {
                $sqlParts .= ',';
            } else {
                $sqlParts .= ';';
            }
        }
        $query = $sql . $sqlParts;
        return $connection->query($query) ? [true, 'success'] : [false, 'error'];
    }


    /**
     * @return array
     */
    public function getAllChangeSizeOrderData()
    {
        $allOrders = $this->orderCollectionFactory->create()->addFieldToSelect('entity_id');
        $changeSizeOrderData = [];
        foreach ($allOrders->getItems() as $order) {
            $method = $order->getPayment()->getMethod();
            if ($method == 'changesizepay') {
                $additional = $order->getPayment()->getAdditionalInformation();
                if (isset($additional['rma_entity_id'])) {
                    $rmaItemId = $additional['rma_entity_id'];
                    $changeSizeOrderData [] = ['rma_item_id' => $rmaItemId, 'order_id' => $order->getEntityId()];
                }
            }
        }

        return $changeSizeOrderData;
    }


}
