<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserSetting extends Model
{
    protected $fillable = [
        'user_id', 
        'setting_key', 
        'setting_value', 
        'setting_type', 
        'description'
    ];

    protected $casts = [
        'setting_value' => 'string',
    ];

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

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

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

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

        // Cast del valore in base al tipo
        return static::castValue($setting->setting_value, $setting->setting_type);
    }

    public static function set($key, $value, $type = 'string', $description = null, $userId = null)
    {
        $userId = $userId ?? auth()->id();
        
        if (!$userId) {
            return false;
        }

        // Se il valore è un array o oggetto, converti in JSON
        if (in_array($type, ['json', 'array']) && !is_string($value)) {
            $value = json_encode($value);
        }

        return static::updateOrCreate(
            ['user_id' => $userId, 'setting_key' => $key],
            [
                'setting_value' => $value,
                'setting_type' => $type,
                'description' => $description
            ]
        );
    }

    /**
     * Cast del valore in base al tipo
     */
    public static function castValue($value, $type)
    {
        switch ($type) {
            case 'boolean':
                return (bool) $value;
            case 'integer':
                return (int) $value;
            case 'json':
            case 'array':
                return json_decode($value, true);
            default:
                return $value;
        }
    }

    /**
     * Ottieni tutte le impostazioni di un utente come array associativo
     */
    public static function getAllForUser($userId = null)
    {
        $userId = $userId ?? auth()->id();
        
        if (!$userId) {
            return [];
        }

        $settings = static::where('user_id', $userId)->get();
        $result = [];

        foreach ($settings as $setting) {
            $result[$setting->setting_key] = static::castValue(
                $setting->setting_value, 
                $setting->setting_type
            );
        }

        return $result;
    }
}
