<?php
namespace Banyo\CustomProduct\Ui\DataProvider\Brand\Form\Modifier;

use Magento\Ui\DataProvider\Modifier\ModifierInterface;
use Magento\Framework\UrlInterface;

class AddProductPageLogo implements ModifierInterface
{
    protected $urlBuilder;

    public function __construct(UrlInterface $urlBuilder)
    {
        $this->urlBuilder = $urlBuilder;
    }

    public function modifyMeta(array $meta)
    {
        // The field is already defined in the XML file, so we don't need to modify the meta
        return $meta;
    }

    public function modifyData(array $data)
    {
        foreach ($data as $id => $brand) {
            // Check if the field exists and is not already in the correct format
            if (isset($brand['brand_product_page_logo']) && !empty($brand['brand_product_page_logo'])) {
                // If it's already an array with the expected structure, leave it alone
                if (is_array($brand['brand_product_page_logo']) &&
                    isset($brand['brand_product_page_logo'][0]['url']) &&
                    isset($brand['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($brand['brand_product_page_logo'])
                    ? ($brand['brand_product_page_logo'][0]['name'] ?? '')
                    : $brand['brand_product_page_logo'];

                if (!empty($fileName)) {
                    $data[$id]['brand_product_page_logo'] = [
                        [
                            'name' => basename($fileName),
                            'url' => $this->getMediaUrl($fileName),
                            'size' => $this->getFileSize($fileName), // Get actual file size if possible
                            'type' => $this->getMimeType($fileName), // Get actual MIME type if possible
                        ]
                    ];
                }
            }
        }
        return $data;
    }

    /**
     * Get the file size
     *
     * @param string $fileName
     * @return int
     */
    protected function getFileSize($fileName)
    {
        $filePath = 'brand/logo/' . ltrim($fileName, '/');
        $mediaDirectory = \Magento\Framework\App\ObjectManager::getInstance()
            ->get(\Magento\Framework\Filesystem::class)
            ->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);

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

        return 0;
    }

    /**
     * Get the MIME type of a file
     *
     * @param string $fileName
     * @return string
     */
    protected 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';
    }

    protected function getMediaUrl($fileName)
    {
        return $this->urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]) . 'brand/logo/' . ltrim($fileName, '/');
    }
}
