<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserSetting extends Model
{
    protected $fillable = ['user_id', 'key', 'value'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public static function get($key, $default = null)
    {
        if (!auth()->check()) {
            return $default;
        }

        $setting = static::where('user_id', auth()->id())
                         ->where('key', $key)
                         ->first();

        return $setting ? $setting->value : $default;
    }

    public static function set($key, $value)
    {
        if (!auth()->check()) {
            return false;
        }

        return static::updateOrCreate(
            ['user_id' => auth()->id(), 'key' => $key],
            ['value' => $value]
        );
    }
}
