<?php

namespace App\Models;

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

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

    // Automatically decrypt when accessing if encrypted
    public function getValueAttribute($value)
    {
        if ($this->is_encrypted && !empty($value)) {
            try {
                return Crypt::decryptString($value);
            } catch (\Exception $e) {
                return $value;
            }
        }
        return $value;
    }

     protected static function booted()
    {
        $clearCache = function ($setting) {
            // Clear all global setting caches whenever a setting is updated
            Cache::forget('seo_settings');
            Cache::forget('site_appearance');
            Cache::forget('post_settings');
            Cache::forget('social_settings');
            Cache::forget('pwa_settings');
            Cache::forget('global_scripts');
            Cache::forget('permalink_structure');
            Cache::forget("settings.{$setting->group}");
        };

        static::saved($clearCache);
        static::deleted($clearCache);
    }
}