<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ParameterGlobal extends Model
{
    use HasFactory;

    protected $table = 'm_parameter_globals';

    protected $fillable = [
        'key',
        'value',
        'description',
        'crated_at',
        'cupdated_at',
        'updated_by'
    ];

    /**
     * Get parameter value by key
     * 
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    public static function getValue($key, $default = null)
    {
        $parameter = static::where('key', $key)->first();
        return $parameter ? $parameter->value : $default;
    }

    /**
     * Get session lifetime in minutes
     * 
     * @return int
     */
    public static function getSessionLifetime()
    {
        return (int) static::getValue('session_lifetime', config('session.lifetime', 120));
    }

    /**
     * Set parameter value
     * 
     * @param string $key
     * @param mixed $value
     * @param string $description
     * @return ParameterGlobal
     */
    public static function setValue($key, $value, $description = null)
    {
        return static::updateOrCreate(
            ['key' => $key],
            [
                'value' => $value,
                'description' => $description,
                'updated_by' => auth()->id()
            ]
        );
    }
}
