<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;

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

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

        if ($setting->type === 'encrypted') {
            try {
                return Crypt::decryptString($setting->value);
            } catch (\Exception $e) {
                return $setting->value; // Return as-is if decryption fails
            }
        }

        return $setting->value ?? $default;
    }

    /**
     * Set setting value by key
     */
    public static function set($key, $value, $type = 'text', $description = null)
    {
        $setting = self::firstOrNew(['key' => $key]);
        
        if ($type === 'encrypted' && $value !== null && $value !== '') {
            try {
                $value = Crypt::encryptString($value);
            } catch (\Exception $e) {
                // If encryption fails, store as plain text
                $value = $value;
            }
        }

        $setting->value = $value;
        $setting->type = $type;
        if ($description) {
            $setting->description = $description;
        }
        $setting->save();

        return $setting;
    }

    /**
     * Accessor for decrypted value
     */
    public function getDecryptedValueAttribute()
    {
        if ($this->type === 'encrypted') {
            try {
                return Crypt::decryptString($this->value);
            } catch (\Exception $e) {
                return $this->value;
            }
        }
        return $this->value;
    }
}
