<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Mtc\MercuryDataModels\PropertyCategory;

class PropertyCategorySitemapController extends Controller
{
    public function index(): Response
    {
        $categories = PropertyCategory::query()
            ->get()
            ->map(fn(PropertyCategory $category) => [
                'id' => $category->id,
                'name' => $category->name,
                'slug' => $category->slug,
                'active' => $category->active,
                'sitemap_enabled' => $category->data['sitemap_enabled'] ?? false,
                'sitemap_base_path' => $category->data['sitemap_base_path'] ?? '/' . $category->slug,
            ]);

        return response($categories);
    }

    public function update(Request $request): Response
    {
        $categories = $request->input('categories', []);

        foreach ($categories as $categoryData) {
            $category = PropertyCategory::query()->find($categoryData['id']);
            if ($category) {
                $data = $category->data ?? [];
                $data['sitemap_enabled'] = $categoryData['sitemap_enabled'] ?? false;
                $data['sitemap_base_path'] = $categoryData['sitemap_base_path'] ?? '/' . $category->slug;
                $category->data = $data;
                $category->save();
            }
        }

        return response('ok');
    }
}
