<?php

namespace App\Models;

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

class Setting extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'key',
        'value',
        'type',
        'category',
        'description',
        'is_active',
        'is_encrypted',
        'validation_rules',
        'options',
        'sort_order'
    ];

    protected $casts = [
        'value' => 'json',
        'is_active' => 'boolean',
        'is_encrypted' => 'boolean',
        'validation_rules' => 'array',
        'options' => 'array',
        'sort_order' => 'integer'
    ];

    /**
     * Get the decrypted value if encrypted
     */
    public function getDecryptedValueAttribute()
    {
        if ($this->is_encrypted && $this->value) {
            return decrypt($this->value);
        }
        
        return $this->value;
    }

    /**
     * Set encrypted value if needed
     */
    public function setEncryptedValue($value)
    {
        if ($this->is_encrypted) {
            $this->value = encrypt($value);
        } else {
            $this->value = $value;
        }
    }

    /**
     * Scope for active settings
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope for settings by category
     */
    public function scopeByCategory($query, $category)
    {
        return $query->where('category', $category);
    }

    /**
     * Get all categories
     */
    public static function getCategories()
    {
        return self::select('category')
            ->distinct()
            ->whereNotNull('category')
            ->pluck('category')
            ->toArray();
    }

    /**
     * Get setting value by key
     */
    public static function getValue($key, $default = null)
    {
        $setting = self::where('key', $key)->where('is_active', true)->first();
        
        if (!$setting) {
            return $default;
        }

        return $setting->is_encrypted ? $setting->getDecryptedValueAttribute() : $setting->value;
    }

    /**
     * Set setting value by key
     */
    public static function setValue($key, $value, $type = 'string', $category = 'general')
    {
        $setting = self::firstOrNew(['key' => $key]);
        
        $setting->type = $type;
        $setting->category = $category;
        $setting->is_active = true;
        
        if ($setting->is_encrypted) {
            $setting->setEncryptedValue($value);
        } else {
            $setting->value = $value;
        }
        
        $setting->save();
        
        return $setting;
    }
}