<?php
/**
 * Mirasvit
 *
 * This source file is subject to the Mirasvit Software License, which is available at https://mirasvit.com/license/.
 * Do not edit or add to this file if you wish to upgrade the to newer versions in the future.
 * If you wish to customize this module for your needs.
 * Please refer to http://www.magentocommerce.com for more information.
 *
 * @category  Mirasvit
 * @package   mirasvit/module-rma
 * @version   2.2.25
 * @copyright Copyright (C) 2023 Mirasvit (https://mirasvit.com/)
 */



namespace Mirasvit\Rma\Model;

use Magento\Framework\DataObject\IdentityInterface;
use Mirasvit\Core\Api\TextHelperInterface;
use Mirasvit\Rma\Api\Config\RmaConfigInterface;
use Mirasvit\Rma\Service\Config\AttachmentConfig;
use Mirasvit\Rma\Service\Config\RmaConfig as RmaService;

class Attachment extends \Magento\Framework\Model\AbstractModel
    implements IdentityInterface, \Mirasvit\Rma\Api\Data\AttachmentInterface
{
    const CACHE_TAG = 'rma_attachment';

    /**
     * {@inheritdoc}
     */
    protected $_cacheTag = 'rma_attachment';

    /**
     * {@inheritdoc}
     */
    protected $_eventPrefix = 'rma_attachment';

    protected $rmaConfig;

    protected $rmaService;

    protected $mstCoreString;

    protected $context;

    protected $registry;

    protected $resourceCollection;

    public function __construct(
        RmaConfigInterface $rmaConfig,
        RmaService $rmaService,
        TextHelperInterface $mstCoreString,
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
        \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
        array $data = []
    ) {
        $this->rmaConfig          = $rmaConfig;
        $this->rmaService         = $rmaService;
        $this->mstCoreString      = $mstCoreString;
        $this->context            = $context;
        $this->registry           = $registry;
        $this->resource           = $resource;
        $this->resourceCollection = $resourceCollection;

        parent::__construct($context, $registry, $resource, $resourceCollection, $data);
    }

    /**
     * {@inheritdoc}
     */
    public function getIdentities()
    {
        return [self::CACHE_TAG.'_'.$this->getId()];
    }

    /**
     * {@inheritdoc}
     */
    protected function _construct()
    {
        $this->_init('Mirasvit\Rma\Model\ResourceModel\Attachment');
    }

    /**
     * {@inheritdoc}
     */
    public function getItemType()
    {
        return $this->getData(self::KEY_ITEM_TYPE);
    }

    /**
     * {@inheritdoc}
     */
    public function setItemType($itemType)
    {
        return $this->setData(self::KEY_ITEM_TYPE, $itemType);
    }

    /**
     * {@inheritdoc}
     */
    public function getItemId()
    {
        return $this->getData(self::KEY_ITEM_ID);
    }

    /**
     * {@inheritdoc}
     */
    public function setItemId($itemId)
    {
        return $this->setData(self::KEY_ITEM_ID, $itemId);
    }

    /**
     * {@inheritdoc}
     */
    public function getUid()
    {
        if (!$this->getData(self::KEY_UID)){
            $uid = hash('sha256',
                (new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT) .
                $this->mstCoreString->generateRandHeavy(100)
            );
            $this->setData(self::KEY_UID, $uid);
        }

        return $this->getData(self::KEY_UID);
    }

    /**
     * {@inheritdoc}
     */
    public function setUid($uid)
    {
        return $this->setData(self::KEY_UID, $uid);
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->getData(self::KEY_NAME);
    }

    /**
     * {@inheritdoc}
     */
    public function setName($name)
    {
        return $this->setData(self::KEY_NAME, $name);
    }

    /**
     * {@inheritdoc}
     */
    public function getType()
    {
        return $this->getData(self::KEY_TYPE);
    }

    /**
     * {@inheritdoc}
     */
    public function setType($type)
    {
        return $this->setData(self::KEY_TYPE, $type);
    }

    /**
     * {@inheritdoc}
     */
    public function getSize()
    {
        return $this->getData(self::KEY_SIZE);
    }

    /**
     * {@inheritdoc}
     */
    public function setSize($size)
    {
        return $this->setData(self::KEY_SIZE, $size);
    }

    /**
     * {@inheritdoc}
     */
    public function getBody()
    {
        if ($this->rmaConfig->getGeneralAttachmentStorage() == AttachmentConfig::ATTACHMENT_STORAGE_FS) {
            if (file_exists($this->rmaConfig->getExternalPath($this->getUid()))) {
                return file_get_contents($this->rmaConfig->getExternalPath($this->getUid()));
            } else {
                throw new \Exception('The file doesn\'t exist or was deleted');
            }
        }

        return $this->getData('body');
    }

    /**
     * {@inheritdoc}
     */
    public function setBody($body)
    {
        $uid = $this->getUid();
        if ($this->rmaConfig->getGeneralAttachmentStorage() == AttachmentConfig::ATTACHMENT_STORAGE_FS) {
            try {
                if (!file_exists(dirname($this->rmaConfig->getExternalPath($uid)))) {
                    mkdir(dirname($this->rmaConfig->getExternalPath($uid)), 0777, true);
                }
                $attachFile = fopen($this->rmaConfig->getExternalPath($uid), 'w');

                fwrite($attachFile, $body);
                fclose($attachFile);
            } catch (\Exception $e) {
                throw new \Magento\Framework\Exception\LocalizedException(__(
                    "Can't write {$this->getName()}"
                ));
            }
            $this->setStorage(AttachmentConfig::ATTACHMENT_STORAGE_FS);
        } else {
            $this->setData('body', $body);
            $this->setStorage(AttachmentConfig::ATTACHMENT_STORAGE_DB);
        }
        $this->getResource()->save($this);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getCreatedAt()
    {
        return $this->getData(self::KEY_CREATED_AT);
    }

    /**
     * {@inheritdoc}
     */
    public function setCreatedAt($createdAt)
    {
        return $this->setData(self::KEY_CREATED_AT, $createdAt);
    }
}
