<?php

namespace FiloBlu\Rma\Helper;

use FiloBlu\Rma\Model\RmaItemResolutionHistoryFactory;
use FiloBlu\Rma\Model\RmaItemResolutionHistoryRepository;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Rma\Api\Data\RmaInterface;
use Magento\Rma\Api\RmaRepositoryInterface;

class RmaItemResolutionHistoryHelper extends AbstractHelper
{
    /**
     * @var RmaItemResolutionHistoryFactory
     */
    protected $itemResolutionHistoryFactory;
    /**
     * @var RmaRepositoryInterface
     */
    protected $rmaRepository;
    /**
     * @var RmaItemResolutionHistoryRepository
     */
    private $rmaItemResolutionHistoryRepository;

    /**
     * @param Context $context
     * @param RmaItemResolutionHistoryFactory $itemResolutionHistoryFactory
     * @param RmaRepositoryInterface $rmaRepository
     * @param RmaItemResolutionHistoryRepository $rmaItemResolutionHistoryRepository
     */
    public function __construct(
        Context $context,
        RmaItemResolutionHistoryFactory $itemResolutionHistoryFactory,
        RmaRepositoryInterface $rmaRepository,
        RmaItemResolutionHistoryRepository $rmaItemResolutionHistoryRepository
    )
    {
        parent::__construct($context);
        $this->itemResolutionHistoryFactory = $itemResolutionHistoryFactory;
        $this->rmaRepository = $rmaRepository;
        $this->rmaItemResolutionHistoryRepository = $rmaItemResolutionHistoryRepository;
    }

    public function saveData($item)
    {
        $itemId = (int)$item->getId();

        if (!$itemId) {
            return false;
        }

        $parentId = (int)$item->getRmaEntityId();
        $rma = $this->rmaRepository->get($parentId);
        $parentIncrementId = $rma->getIncrementId();
        $resolution = $item->getResolution();

        if (empty($resolution)) {
            return false;
        }

        $url = $_SERVER['REQUEST_URI'];

        if ($this->rmaItemResolutionHistoryRepository->getByItemIdAndUrl($itemId, $url)) {
            return false;
        }


        $createdAt = date('Y-m-d H:i:s');
        $updatedAt = date('Y-m-d H:i:s');

        $itemResolutionHistoryFactory = $this->itemResolutionHistoryFactory->create();
        $itemResolutionHistoryFactory->setData([
            'item_id' => $itemId,
            'parent_id' => $parentId,
            'parent_increment_id' => $parentIncrementId,
            'resolution' => $resolution,
            'url' => $url,
            'created_at' => $createdAt,
            'updated_at' => $updatedAt,
        ]);

        try {
            $itemResolutionHistoryFactory->save();
        } catch (\Exception $e) {

        }
    }

    public function saveRmaItemsData(RmaInterface $rma) {

        foreach ($rma->getItems() as $item) {
            $this->saveData($item);
        }

    }
}
