<?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.1.31
 * @copyright Copyright (C) 2021 Mirasvit (https://mirasvit.com/)
 */



namespace Mirasvit\Rma\Plugin\Attachment;

use Mirasvit\Rma\Api\Data\AttachmentInterface;
use Mirasvit\Rma\Service\Config\AttachmentConfig;
use Mirasvit\Rma\Service\Config\RmaConfig;
use Mirasvit\Core\Api\TextHelperInterface;
use Mirasvit\Rma\Model\Attachment;

class SetDefaultsBeforeCreatePlugin
{
    private   $mstCoreString;

    protected $config;

    protected $rmaAttachment;

    public function __construct(
        TextHelperInterface $mstCoreString,
        RmaConfig           $config,
        Attachment          $rmaAttachment
    ) {
        $this->mstCoreString = $mstCoreString;
        $this->config        = $config;
        $this->rmaAttachment = $rmaAttachment;
    }

    /**
     * @param AttachmentInterface $attachment
     *
     * @return void
     */
    public function beforeSave(AttachmentInterface $attachment)
    {
        if ($attachment->getId()) {
            return;
        }

        $uid = hash('sha256',
            (new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT) .
            $this->mstCoreString->generateRandHeavy(100)
        );
        $attachment->setUid($uid);

        if ($this->config->getGeneralAttachmentStorage() == AttachmentConfig::ATTACHMENT_STORAGE_FS) {

            try {
                if (!file_exists(dirname($this->getExternalPath($uid)))) {
                    mkdir(dirname($this->getExternalPath($uid)), 0777, true);
                }
                $attachFile = fopen($this->getExternalPath($uid), 'w');

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

    /**
     * @param string $uid
     *
     * @return string
     */
    public function getExternalPath($uid)
    {
        return $this->config->getAttachmentFolderPath() .
            substr($uid, 0, 1) . '/' . substr($uid, 1, 2) . '/' . $uid;
    }
}
