<?php

namespace App\Core\Settings\Controllers;

use App\Controllers\BaseController;
use App\Core\Audit\Services\AuditService;
use App\Core\Settings\Services\SettingService;

class SettingsController extends BaseController
{
    public function index()
    {
        return view('core/settings/index', [
            'title' => 'Paramètres',
            'groups' => (new SettingService())->grouped(),
        ]);
    }

    public function save()
    {
        $settings = new SettingService();
        foreach ((array) $this->request->getPost('settings') as $key => $value) {
            $key = (string) $key;
            $encrypted = $key === 'openai.api_key';
            $value = is_array($value) ? null : (string) $value;

            if ($encrypted && trim((string) $value) === '') {
                continue;
            }

            $settings->set($key, $value, 'general', $encrypted);
        }

        (new AuditService())->log('settings.update', 'settings', null, 'Mise à jour des paramètres');

        return redirect()->back()->with('success', 'Paramètres enregistrés.');
    }
}
