<?php

namespace App\Http\Controllers\Api\GoPoints;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Support\Str;

class QueryProductController extends Controller
{
    /**
     * GET /api/gopoints/product/{campaign}/{sku}
     * Devuelve 1 producto con la estructura del manual.
     */
    public function show($campaign, $sku)
    {
        // 1) Validar campaña
        if (Str::lower($campaign) !== 'gopoints') {
            return response()->json([
                'Status'    => 400,
                'Message'   => 'Campaña no reconocida',
                'CodeError' => 'INVALID_CAMPAIGN',
                'Exception' => null,
            ], 400, [], JSON_UNESCAPED_UNICODE);
        }

        // 2) Buscar producto por SKU
        $p = Product::where('sku', $sku)->first();

        // 3) No encontrado
        if (!$p) {
            return response()->json([
                'Status'    => 404,
                'Message'   => 'Producto no encontrado',
                'CodeError' => 'PRODUCT_NOT_FOUND',
                'Exception' => null,
            ], 404, [], JSON_UNESCAPED_UNICODE);
        }

        // 4) Mapear categorías (CSV -> array)
        $categories = [];
        if (!empty($p->category)) {
            $categories = array_values(array_filter(array_map('trim', explode(',', $p->category))));
        }

        // 5) Mapear fotos (CSV -> [{Position, Url}])
        $photos = [];
        if (!empty($p->image)) {
            $urls = array_values(array_filter(array_map('trim', explode(',', $p->image))));
            foreach ($urls as $i => $url) {
                $photos[] = [
                    'Position' => $i + 1,
                    'Url'      => $url,
                ];
            }
        }

        // 6) Construir el producto con claves en inglés (consistencia con /products)
        $product = [
            'Sku'         => (string) $p->sku,
            'Name'        => (string) $p->name,
            'Description' => strip_tags((string) $p->description),
            'PriceBefore' => (float) ($p->price_before ?? $p->price),
            'Price'       => (float) $p->price,
            'Available'   => (bool) $p->active,
            'Quantity'    => (int)  $p->stock,
            'Photos'      => $photos,
            'Categories'  => $categories,
        ];

        // 7) Respuesta final (bloque de estado primero, Message vacío en éxito)
        return response()->json([
            'Status'    => 200,
            'Message'   => '',
            'CodeError' => '',
            'Exception' => null,
            'Product'   => $product,
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }
}
