<?php
declare(strict_types=1);

namespace App\Modules\Settings\Models;

use App\Core\App;

class SystemConfig
{
    public static function getAllGrouped(): array
    {
        $db = App::getInstance()->db();
        $rows = $db->select("SELECT * FROM system_config ORDER BY group_name, config_key");
        $grouped = [];
        foreach ($rows as $row) {
            $grouped[$row['group_name']][] = $row;
        }
        return $grouped;
    }

    public static function getByGroup(string $group): array
    {
        $db = App::getInstance()->db();
        return $db->select("SELECT * FROM system_config WHERE group_name = ? ORDER BY config_key", [$group]);
    }

    public static function get(string $key): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne("SELECT * FROM system_config WHERE config_key = ?", [$key]);
    }

    public static function set(string $key, string $value): void
    {
        $db = App::getInstance()->db();
        $existing = $db->selectOne("SELECT id FROM system_config WHERE config_key = ?", [$key]);
        if ($existing) {
            $db->update('system_config', [
                'config_value' => $value,
                'updated_at'   => date('Y-m-d H:i:s'),
            ], '`id` = ?', [$existing['id']]);
        } else {
            $group = 'general';
            if (str_contains($key, '.')) {
                $group = explode('.', $key, 2)[0];
            }
            $db->insert('system_config', [
                'config_key'   => $key,
                'config_value' => $value,
                'config_type'  => 'string',
                'group_name'   => $group,
                'is_editable'  => 1,
                'created_at'   => date('Y-m-d H:i:s'),
                'updated_at'   => date('Y-m-d H:i:s'),
            ]);
        }
    }

    public static function getGroups(): array
    {
        $db = App::getInstance()->db();
        $rows = $db->select("SELECT DISTINCT group_name FROM system_config ORDER BY group_name");
        return array_column($rows, 'group_name');
    }
}