<?php
namespace Banyo\CustomProduct\Plugin;

use Mirasvit\Brand\Ui\BrandPage\Form\DataProvider;
use Magento\Framework\UrlInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;

class DataProviderPlugin
{
    /**
     * @var UrlInterface
     */
    private $urlBuilder;

    /**
     * @var \Magento\Framework\Filesystem\Directory\ReadInterface
     */
    private $mediaDirectory;

    /**
     * @param UrlInterface $urlBuilder
     * @param Filesystem $filesystem
     */
    public function __construct(
        UrlInterface $urlBuilder,
        Filesystem $filesystem
    ) {
        $this->urlBuilder = $urlBuilder;
        $this->mediaDirectory = $filesystem->getDirectoryRead(DirectoryList::MEDIA);
    }

    /**
     * Add our custom field data to the result
     *
     * @param DataProvider $subject
     * @param array $result
     * @return array
     */
    public function afterGetData(DataProvider $subject, array $result)
    {
        foreach ($result as $id => $brandData) {
            // Check if the field exists and is not already in the correct format
            if (isset($brandData['brand_product_page_logo']) && !empty($brandData['brand_product_page_logo'])) {
                // If it's already an array with the expected structure, leave it alone
                if (is_array($brandData['brand_product_page_logo']) &&
                    isset($brandData['brand_product_page_logo'][0]['url']) &&
                    isset($brandData['brand_product_page_logo'][0]['name'])) {
                    continue;
                }

                // If it's a string or an array without the expected structure, format it correctly
                $fileName = is_array($brandData['brand_product_page_logo'])
                    ? ($brandData['brand_product_page_logo'][0]['name'] ?? '')
                    : $brandData['brand_product_page_logo'];

                if (!empty($fileName)) {
                    $result[$id]['brand_product_page_logo'] = [
                        [
                            'name' => $fileName,
                            'url' => $this->getMediaUrl($fileName),
                            'size' => $this->getFileSize($fileName),
                            'type' => $this->getMimeType($fileName),
                        ]
                    ];
                }
            }
        }

        return $result;
    }

    /**
     * Get the media URL for a file
     *
     * @param string $fileName
     * @return string
     */
    private function getMediaUrl($fileName)
    {
        return $this->urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]) . 'brand/logo/' . ltrim($fileName, '/');
    }

    /**
     * Get the file size
     *
     * @param string $fileName
     * @return int
     */
    private function getFileSize($fileName)
    {
        $filePath = 'brand/logo/' . ltrim($fileName, '/');

        if ($this->mediaDirectory->isExist($filePath)) {
            return $this->mediaDirectory->stat($filePath)['size'];
        }

        return 0;
    }

    /**
     * Get the MIME type of a file
     *
     * @param string $fileName
     * @return string
     */
    private function getMimeType($fileName)
    {
        $extension = pathinfo($fileName, PATHINFO_EXTENSION);

        $mimeTypes = [
            'jpg' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
            'svg' => 'image/svg+xml',
        ];

        return $mimeTypes[strtolower($extension)] ?? 'application/octet-stream';
    }
}
