<?php

namespace App\Http\Controllers\Api\GoPoints;

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

class CategoriesController extends Controller
{
    
    public function show($campaign)
    {
        $campaignNormalized = trim(Str::lower($campaign));

        if ($campaignNormalized !== 'gopoints') {
            return response()->json([
                "Status" => 400,
                "Message" => "Campaña no reconocida",
                "CodeError" => "INVALID_CAMPAIGN",
                "Exception" => null
            ], 400);
        }

        $rootCategories = Category::whereNull('parent_id')
            ->select('id', 'code', 'name')
            ->orderBy('name')
            ->get();

        $categoriesTree = $rootCategories->map(function ($cat) {
            return [
                "Code" => (string) $cat->code,
                "Name" => $cat->name,
                "Categories" => $this->getSubcategories($cat->id)
            ];
        });

        return response()->json([
            "Categories" => $categoriesTree,
            "Status" => 200,
            "Message" => "Categorías obtenidas correctamente",
            "CodeError" => "",
            "Exception" => null
        ], 200);
    }

   
    private function getSubcategories($parentId)
    {
        $subcategories = Category::where('parent_id', $parentId)
            ->select('id', 'code', 'name', 'parent_id')
            ->orderBy('name')
            ->get();

        if ($subcategories->isEmpty()) {
            return [];
        }

        return $subcategories->map(function ($sub) {
            return [
                "Code" => (string) $sub->code,
                "Name" => $sub->name,
                "Categories" => $this->getSubcategories($sub->id)
            ];
        });
    }
}
