<?php

namespace PrestaShop\Module\LCVPrestaTheme\Controllers\Admin;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Product;
use Image;
use Link;
use Context;

class ProductSearchController extends  AdminFormController
{
    public function searchAction(Request $request): JsonResponse
    {

    
        $query = trim($request->query->get('q', ''));

        if (empty($query)) {
            return new JsonResponse([]);
        }

        $langId   = (int) Context::getContext()->language->id;
        $shopId   = (int) Context::getContext()->shop->id;
        $link     = new Link();
        $results  = [];

        // ------------------------------------------------
        // CAS 1 : recherche par ID
        // ------------------------------------------------
        if (is_numeric($query)) {

            $product = new Product((int) $query, false, $langId, $shopId);

            if (!$product->id) {
                return new JsonResponse([]);
            }

            $results[] = $this->formatProduct($product, $langId, $link);

        // ------------------------------------------------
        // CAS 2 : recherche par nom
        // ------------------------------------------------
        } else {

            $sql = new \DbQuery();
            $sql->select('p.id_product');
            $sql->from('product', 'p');
            $sql->innerJoin('product_lang', 'pl', '
                pl.id_product = p.id_product
                AND pl.id_lang = ' . $langId . '
                AND pl.id_shop = ' . $shopId
            );
            $sql->where('pl.name LIKE "%' . pSQL($query) . '%"');
            $sql->where('p.active = 1');
            $sql->limit(8);

            $rows = \Db::getInstance()->executeS($sql);

            if (empty($rows)) {
                return new JsonResponse([]);
            }

            foreach ($rows as $row) {
                $product = new Product((int) $row['id_product'], false, $langId, $shopId);
                $results[] = $this->formatProduct($product, $langId, $link);
            }
        }

        return new JsonResponse($results);
    }


    // -------------------------------------------------------
    // Formate un produit pour la réponse JSON
    // -------------------------------------------------------
    private function formatProduct(Product $product, int $langId, Link $link): array
    {
        // Nom — PS9 retourne soit un tableau soit une string selon le contexte
        if (is_array($product->name)) {
            $name = $product->name[$langId] ?? reset($product->name);
        } else {
            $name = $product->name;
        }

        // Image
        $imageUrl = null;
        $cover = Product::getCover($product->id);

        if ($cover) {
            $imageUrl = $link->getImageLink(
                is_array($product->link_rewrite) 
                    ? ($product->link_rewrite[$langId] ?? reset($product->link_rewrite))
                    : $product->link_rewrite,
                (int)$cover['id_image'],
                'small_default' // 👈 format plus fiable que home_default
            );

            // Ajoute le protocole si absent
            if (!str_starts_with($imageUrl, 'http')) {
                $imageUrl = 'http://' . $imageUrl;
            }
        }

        return [
            'id'    => $product->id,
            'name'  => $name,
            'image' => $imageUrl,
        ];
    }
}