<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class SystemConfiguration extends Model
{
    protected $table = 'system_configurations';

    protected $fillable = ['key', 'value'];

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * Get the value attribute
     */
    public function getValueAttribute($value)
    {
        if (json_validate($value)) {
            return json_decode($value, true);
        }
        return $value;
    }

    /**
     * Set the value attribute
     */
    public function setValueAttribute($value)
    {
        if (is_array($value) || is_object($value)) {
            $this->attributes['value'] = json_encode($value);
        } else {
            $this->attributes['value'] = $value;
        }
    }

    /**
     * Find configuration by key
     */
    public static function findByKey($key)
    {
        return static::where('key', $key)->first();
    }

    /**
     * Get all configurations as key-value pairs
     */
    public static function getAllAsArray()
    {
        $configs = static::all();
        $result = [];

        foreach ($configs as $config) {
            $result[$config->key] = $config->value;
        }

        return $result;
    }
}

