<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;

class SettingController extends Controller
{
    /** All settings merged over defaults. */
    public function index()
    {
        return response()->json(['data' => Setting::allSettings()]);
    }

    /** Bulk update settings. Only known keys are accepted. */
    public function update(Request $request)
    {
        $data = $request->validate([
            'settings' => ['required', 'array'],
        ]);

        $allowed = array_keys(Setting::$defaults);

        foreach ($data['settings'] as $key => $value) {
            if (! in_array($key, $allowed, true)) {
                continue;
            }
            // Store booleans as "1"/"0" strings for consistency.
            if (is_bool($value)) {
                $value = $value ? '1' : '0';
            }
            Setting::set($key, $value ?? '');
        }

        return response()->json(['data' => Setting::allSettings()]);
    }
}
