<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class SystemConfiguration extends Model
{
    protected $fillable = [
        'key',
        'value',
        'type',
        'category',
        'description'
    ];

    protected $casts = [
        'value' => 'string'
    ];

    /**
     * Get configuration value by key
     */
    public static function getValue($key, $default = null)
    {
        $config = static::where('key', $key)->first();

        if (!$config) {
            return $default;
        }

        switch ($config->type) {
            case 'json':
                return json_decode($config->value, true);
            case 'boolean':
                return filter_var($config->value, FILTER_VALIDATE_BOOLEAN);
            case 'number':
                return is_numeric($config->value) ? (float) $config->value : $config->value;
            default:
                return $config->value;
        }
    }

    /**
     * Set configuration value
     */
    public static function setValue($key, $value, $type = 'string', $category = 'general', $description = null)
    {
        // Convert value based on type
        switch ($type) {
            case 'json':
                $value = json_encode($value);
                break;
            case 'boolean':
                $value = $value ? 'true' : 'false';
                break;
        }

        return static::updateOrCreate(
            ['key' => $key],
            [
                'value' => $value,
                'type' => $type,
                'category' => $category,
                'description' => $description
            ]
        );
    }

    /**
     * Get occupation options
     */
    public static function getOccupationOptions()
    {
        return static::getValue('occupation_options', []);
    }

    /**
     * Get the parsed value attribute
     */
    public function getParsedValueAttribute()
    {
        switch ($this->type) {
            case 'json':
                return json_decode($this->value, true);
            case 'boolean':
                return filter_var($this->value, FILTER_VALIDATE_BOOLEAN);
            case 'number':
                return is_numeric($this->value) ? (float) $this->value : $this->value;
            default:
                return $this->value;
        }
    }
}
