<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\BaseController;
use App\Models\Setting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdminSettingController extends BaseController
{
    public function index(Request $request): JsonResponse
    {
        $group = $request->get('group', 'general');
        $settings = Setting::where('group', $group)->get();
        return $this->successResponse($settings);
    }

    public function update(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'settings' => ['required', 'array'],
            'settings.*.key' => ['required', 'string'],
            'settings.*.value' => ['required'],
            'settings.*.type' => ['sometimes', 'in:string,boolean,integer,float,json'],
        ]);

        foreach ($validated['settings'] as $setting) {
            Setting::setValue($setting['key'], $setting['value'], $setting['type'] ?? 'string');
        }

        return $this->successResponse(null, 'Settings updated');
    }

    public function maintenance(Request $request): JsonResponse
    {
        $request->validate([
            'enabled' => ['required', 'boolean'],
        ]);

        Setting::setValue('maintenance_mode', $request->boolean('enabled'), 'boolean');

        return $this->successResponse(null, 'Maintenance mode ' . ($request->boolean('enabled') ? 'enabled' : 'disabled'));
    }
}
