<?php

namespace App\Http\Controllers;

use App\Models\Activity;
use App\Models\Member;
use App\Models\SiteSetting;
use App\Models\Team;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SiteSettingController extends Controller
{
    public function index(): JsonResponse
    {
        $settings = SiteSetting::orderBy('group')->orderBy('sort_order')->orderBy('id')->get();
        return response()->json(['data' => $settings]);
    }

    public function publicIndex(): JsonResponse
    {
        $settings = SiteSetting::whereIn('group', ['login_hero', 'login_form', 'recap', 'weekly_focus'])
            ->orderBy('sort_order')
            ->get(['key', 'value']);
        return response()->json(['data' => $settings->pluck('value', 'key')]);
    }

    public function publicStats(): JsonResponse
    {
        return response()->json([
            'data' => [
                'teams' => Team::count(),
                'members' => Member::count(),
                'weeks' => 6,
                'activities' => Activity::count(),
            ],
        ]);
    }

    public function bulkUpdate(Request $request): JsonResponse
    {
        $data = $request->validate([
            'settings' => ['required', 'array', 'min:1'],
            'settings.*.key' => ['required', 'string', 'exists:site_settings,key'],
            'settings.*.value' => ['nullable', 'string', 'max:2000'],
        ]);

        foreach ($data['settings'] as $row) {
            SiteSetting::where('key', $row['key'])->update(['value' => $row['value'] ?? '']);
        }

        return $this->index();
    }
}
