<?php

namespace App\Http\Controllers\Admin\Ai;

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

class SettingsController extends Controller
{
    public function index()
    {
        $settings = Setting::all()->pluck('value', 'key')->toArray();

        return view('admin.ai.settings', [
            'settings' => $settings,
        ]);
    }

    public function update(Request $request)
    {
        $request->validate([
            'ai_api_base_url' => 'nullable|string|max:255',
            'ai_model' => 'nullable|string|max:100',
            'ai_api_key' => 'nullable|string|max:255',
            'ai_api_key_clear' => 'nullable|boolean',
            'ai_language' => 'nullable|in:en,bn',
            'ai_tone' => 'nullable|in:neutral,friendly,formal',
            'ai_temperature' => 'nullable|numeric|min:0|max:1',
            'removebg_api_url' => 'nullable|string|max:255',
            'removebg_api_key' => 'nullable|string|max:255',
            'removebg_api_key_clear' => 'nullable|boolean',
        ]);

        $fields = [
            'ai_api_base_url',
            'ai_model',
            'ai_language',
            'ai_tone',
            'ai_temperature',
            'removebg_api_url',
        ];

        foreach ($fields as $key) {
            if ($request->has($key)) {
                Setting::updateOrCreate(
                    ['key' => $key],
                    ['value' => $request->input($key)]
                );
            }
        }

        if ($request->filled('ai_api_key')) {
            Setting::updateOrCreate(
                ['key' => 'ai_api_key'],
                ['value' => $request->input('ai_api_key')]
            );
        } elseif ($request->boolean('ai_api_key_clear')) {
            Setting::updateOrCreate(
                ['key' => 'ai_api_key'],
                ['value' => null]
            );
        }

        if ($request->filled('removebg_api_key')) {
            Setting::updateOrCreate(
                ['key' => 'removebg_api_key'],
                ['value' => $request->input('removebg_api_key')]
            );
        } elseif ($request->boolean('removebg_api_key_clear')) {
            Setting::updateOrCreate(
                ['key' => 'removebg_api_key'],
                ['value' => null]
            );
        }

        return redirect()
            ->route('admin.ai.settings.index')
            ->with('success', 'AI settings updated successfully.');
    }
}
