<?php

namespace MGS\FakeOrder\Model\Api;

use Magento\Catalog\Helper\Image as ImageHelper;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\App\RequestInterface;
use MGS\FakeOrder\Api\fakeOrderInterface;

class FakeOrderApi implements fakeOrderInterface
{
    protected $productCollectionFactory;
    protected $resultJsonFactory;
    protected $imageHelper;
    protected $request;

    public function __construct(
        CollectionFactory $productCollectionFactory,
        ImageHelper       $imageHelper,
        JsonFactory $resultJsonFactory,
        RequestInterface $request,
    )
    {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->productCollectionFactory = $productCollectionFactory;
        $this->imageHelper = $imageHelper;
        $this->request = $request;
    }

    /**
     * Get product data with name and thumbnail.
     * @return array[]
     */
    public function getDataProducts()
    {
        $query = $this->request->getParam('q', '');
        try {
            $data = [];
            $collection = $this->productCollectionFactory->create()
                ->addAttributeToSelect(['name', 'small_image'])
                ->addFieldToFilter('name', ['like' => '%' . $query . '%'])
                ->setPageSize(50);

            foreach ($collection as $product) {

                $imageUrl = $this->imageHelper->init($product, 'product_page_image_small')
                    ->setImageFile($product->getSmallImage())
                    ->resize(380)
                    ->getUrl();

                $data[] = [
                    'value'    => $product->getId(),
                    'label'    => $product->getName(),
                    'image'    => $imageUrl,
                    'data-src'    => $imageUrl,
                    'url'      => $product->getProductUrl(),
                ];
            }


            return [[
                        'status'  => 'success',
                        'message' => 'Product data retrieved successfully.',
                        'data'    => $data
                    ]];
        }
        catch (\Exception $e) {
            return  [[
                         'status'  => 'error',
                         'message' => 'Unable to retrieve product data: ' . $e->getMessage()
                     ]];
        }
    }

}
