<?php
class SettingsController extends Controller
{
    public function index(Request $request): void
    {
        $db = $this->db();
        $settings = $db->fetchAll("SELECT * FROM sys_config ORDER BY config_group, id");
        $groups = [];
        foreach ($settings as $s) {
            $groups[$s['config_group']][] = $s;
        }

        $this->view('settings/index', [
            'title' => lang('admin.settings'),
            'breadcrumbs' => [
                ['label' => lang('admin.administration'), 'url' => '/admin/settings'],
                ['label' => lang('admin.settings')]
            ],
            'groups' => $groups,
        ]);
    }

    public function update(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }

        $db = $this->db();
        $configs = $request->post('config', []);
        $updated = 0;

        foreach ($configs as $key => $value) {
            $existing = $db->fetchOne("SELECT id, config_value, is_readonly FROM sys_config WHERE config_key = ?", [$key]);
            if ($existing && !$existing['is_readonly'] && $existing['config_value'] !== $value) {
                $db->update('sys_config', [
                    'config_value' => $value,
                    'updated_by'   => Auth::id(),
                    'updated_at'   => date('Y-m-d H:i:s'),
                ], 'config_key = ?', [$key]);
                $updated++;
            }
        }

        $this->audit('update', 'sys_config', null, "Updated {$updated} settings");
        Config::clearCache();
        $this->json(['success' => true, 'message' => "Updated {$updated} settings"]);
    }
}