<?php
namespace App\Models;

use App\Core\Model;
use PDO;

class Setting extends Model {
    protected static string $table = 'settings';

    public static function getVal(string $key, mixed $default = null): mixed {
        $row = self::firstWhere('key', $key);
        return $row ? $row['value'] : $default;
    }

    public static function setVal(string $key, mixed $value, string $group = 'general'): bool {
        $existing = self::firstWhere('key', $key);
        if ($existing) {
            return self::update((int)$existing['id'], ['value' => (string)$value, 'updated_at' => date('Y-m-d H:i:s')]);
        } else {
            return (bool)self::create([
                'key'   => $key,
                'value' => (string)$value,
                'group' => $group
            ]);
        }
    }

    public static function getAllGrouped(): array {
        $all = self::all('`group` ASC, `key` ASC');
        $grouped = [];
        foreach ($all as $item) {
            $grouped[$item['group']][$item['key']] = $item['value'];
        }
        return $grouped;
    }
}
