<?php

namespace App\Http\Controllers;

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

class FranchiseSitemapController extends Controller
{
    public function index(): Response
    {
        $franchises = Franchise::query()
            ->get()
            ->map(fn (Franchise $franchise) => [
                'id' => $franchise->id,
                'name' => $franchise->name,
                'slug' => $franchise->slug,
                'sitemap_srp_enabled' => $franchise->data['sitemap-srp-enabled'] ?? false,
                'sitemap_srp_path' => $franchise->data['sitemap-srp-path'] ?? '',
                'sitemap_new_cars_enabled' => $franchise->data['sitemap-new-cars-enabled'] ?? true,
            ]);

        return response($franchises);
    }

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

        foreach ($franchises as $franchiseData) {
            $franchise = Franchise::query()->find($franchiseData['id']);
            if ($franchise) {
                $data = $franchise->data ?? [];
                $data['sitemap-srp-enabled'] = $franchiseData['sitemap_srp_enabled'] ?? false;
                $data['sitemap-srp-path'] = $franchiseData['sitemap_srp_path'] ?? '';
                $data['sitemap-new-cars-enabled'] = $franchiseData['sitemap_new_cars_enabled'] ?? false;
                $franchise->data = $data;
                $franchise->save();
            }
        }

        return response('ok');
    }
}
