<?php

namespace FiloBlu\Refilo\Model\CmsPage;

use Magento\Cms\Model\Page\DomValidationState;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Stdlib\DateTime\Filter\Date;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Model\Layout\Update\ValidatorFactory;
use Magento\Store\Model\StoreManagerInterface;

class PostDataProcessor extends \Magento\Cms\Controller\Adminhtml\Page\PostDataProcessor
{
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    public function __construct(
        Date $dateFilter,
        ManagerInterface $messageManager,
        ValidatorFactory $validatorFactory,
        StoreManagerInterface $storeManager,
        DomValidationState $validationState = null
    ) {
        parent::__construct(
            $dateFilter,
            $messageManager,
            $validatorFactory,
            $validationState
        );
        $this->storeManager = $storeManager;
    }

    /**
     * @param array $data
     * @return array
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function filter($data)
    {
        if (isset($data['og_data_image'][0]) || !empty($data['og_data_image'][0])) {
            $url = $data['og_data_image'][0]['url'];
            if (strpos($url, DIRECTORY_SEPARATOR) === 0) {
                $path = str_replace('/media/', '', $url);
            } else {
                $path = str_replace($this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA), '', $url);
            }
            $data['og_data_image'] = $path;
        }

        return parent::filter($data);
    }
}
