<?php

namespace App\Http\Controllers\Api\GoPoints;

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

class CatalogProductsController extends Controller
{
    public function show(Request $request, $campaign)
    {
        // 1) Validación de campaña (case-insensitive)
        if (Str::lower($campaign) !== 'gopoints') {
            return response()->json([
                'Status'    => 400,
                'Message'   => 'Campaña no reconocida',
                'CodeError' => 'INVALID_CAMPAIGN',
                'Exception' => null,
            ], 400, [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }

        // 2) Paginación opcional (según manual: PageSize / PageNumber)
        $pageSize   = (int) $request->query('PageSize', 50);
        $pageNumber = (int) $request->query('PageNumber', 1);

        // límites sanos
        $pageSize   = max(1, min($pageSize, 200));
        $pageNumber = max(1, $pageNumber);

        // 3) Consulta base por campaña
        $query = Product::where('campaign_id', 'GoPoints')->orderBy('id');

        $paginator  = $query->paginate($pageSize, ['*'], 'page', $pageNumber);
        $collection = $paginator->getCollection();

        // 4) Mapeo al esquema EXACTO del manual
        $products = $collection->map(function ($p) {
            // Categories (array de strings)
            $categories = [];
            if (!empty($p->category)) {
                $categories = array_values(array_filter(array_map('trim', explode(',', $p->category))));
            }

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

            // PriceBefore: si no existe, igual al Price (numérico)
            $price = (float) ($p->price ?? 0);
            $priceBefore = (float) ($p->price_before ?? $price);

            return [
                'Sku'         => (string) $p->sku,
                'Name'        => (string) $p->name,
                'Description' => (string) strip_tags((string) $p->description),
                'PriceBefore' => $priceBefore,
                'Price'       => $price,
                'Available'   => (bool) ($p->active && (is_null($p->stock) ? true : ($p->stock > 0))),
                'Quantity'    => (int)   ($p->stock ?? 0),
                'Photos'      => $photos,
                'Categories'  => $categories,
            ];
        })->values();

        // 5) Respuesta según el estándar (Message vacío en éxito)
        $response = [
            'Status'     => 200,
            'Message'    => '',
            'CodeError'  => '',
            'Exception'  => null,
            'Parameters' => [
                'Campaign'   => 'GoPoints',
                'PageSize'   => $pageSize,
                'PageNumber' => $pageNumber,
            ],
            'Products'   => $products,
        ];

        return response()->json(
            $response,
            200,
            [],
            JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
        );
    }
}
