<?php
declare(strict_types=1);

namespace App\Modules\Settings\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Settings\Models\SystemConfig;

class SettingsController extends Controller
{
    public function index(Request $request): Response
    {
        $grouped = SystemConfig::getAllGrouped();
        return $this->view('Settings.Views.index', ['grouped' => $grouped]);
    }

    public function editGroup(Request $request, string $group): Response
    {
        $settings = SystemConfig::getByGroup($group);
        if (empty($settings)) {
            return $this->redirect('/settings')->withError('مجموعة الإعدادات غير موجودة');
        }
        return $this->view('Settings.Views.edit-group', [
            'group'    => $group,
            'settings' => $settings,
        ]);
    }

    public function updateGroup(Request $request, string $group): Response
    {
        $settings = SystemConfig::getByGroup($group);
        if (empty($settings)) {
            return $this->redirect('/settings')->withError('مجموعة الإعدادات غير موجودة');
        }

        $db = App::getInstance()->db();
        $updated = 0;

        foreach ($settings as $setting) {
            if (!$setting['is_editable']) {
                continue;
            }

            $key = $setting['config_key'];
            $newValue = $request->post('config_' . str_replace('.', '_', $key), '');

            if ((string) $newValue !== (string) ($setting['config_value'] ?? '')) {
                SystemConfig::set($key, (string) $newValue);
                $updated++;
            }
        }

        return $this->redirect('/settings')->withSuccess("تم تحديث {$updated} إعداد بنجاح");
    }
}