<?php

namespace Leadlion\SmartBill\Ui\Component\Listing\Column;

use Magento\Backend\Model\UrlInterface;
use Magento\Ui\Component\Listing\Columns\Column;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;

class SmartBillInvoice extends Column
{
    private UrlInterface $backendUrl;

    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        UrlInterface $backendUrl,
        array $components = [],
        array $data = []
    ) {
        $this->backendUrl = $backendUrl;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as &$item) {
                try {
                    if (!empty($item['smartbill_invoice'])) {
                        if (!empty($item['smartbill_document_url'])) {
                            $docUrl = ltrim($item['smartbill_document_url'], '/');
                            // Strip "smartbill/inv/" prefix to get path within var/smartbill/inv/
                            $relPath = preg_replace('#^smartbill/inv/#', '', $docUrl);
                            $downloadUrl = $this->backendUrl->getUrl(
                                'leadlion_smartbill/invoice/download',
                                ['file' => base64_encode($relPath)]
                            );
                            $item[$this->getData('name')] = [
                                'view' => [
                                    'href'   => $downloadUrl,
                                    'label'  => $item['smartbill_invoice'],
                                    'target' => '_blank',
                                ]
                            ];
                        } else {
                            $item[$this->getData('name')] = (string)__('Da');
                        }
                    } else {
                        $item[$this->getData('name')] = (string)__('Nu');
                    }
                } catch (\Exception $e) {
                    $item[$this->getData('name')] = (string)__('Eroare');
                }
            }
        }

        return $dataSource;
    }
}
