<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;

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

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

    // Boot method to clear cache when settings change
    protected static function boot()
    {
        parent::boot();
        
        static::saved(function () {
            self::refreshConfigCache();
        });
        
        static::deleted(function () {
            self::refreshConfigCache();
        });
    }

    // Get setting value with proper type casting
    public function getValueAttribute($value)
    {
        return match($this->type) {
            'boolean' => filter_var($value, FILTER_VALIDATE_BOOLEAN),
            'number' => is_numeric($value) ? (float) $value : 0,
            'json' => json_decode($value, true) ?? [],
            default => $value
        };
    }

    // Set setting value with proper type handling
    public function setValueAttribute($value)
    {
        $this->attributes['value'] = match($this->type) {
            'boolean' => $value ? '1' : '0',
            'json' => is_array($value) ? json_encode($value) : $value,
            default => (string) $value
        };
    }

    // Static method to get setting value
    public static function get($key, $default = null)
    {
        // Try to get from Laravel config first (cached)
        $configKey = "site.{$key}";
        if (Config::has($configKey)) {
            return Config::get($configKey, $default);
        }

        // Fallback to database
        $setting = self::where('key', $key)->first();
        return $setting ? $setting->value : $default;
    }

    // Static method to set setting value
    public static function set($key, $value, $type = 'text', $group = 'general', $description = null)
    {
        return self::updateOrCreate(
            ['key' => $key],
            [
                'value' => $value,
                'type' => $type,
                'group' => $group,
                'description' => $description
            ]
        );
    }

    // Refresh config cache
    public static function refreshConfigCache()
    {
        try {
            // Get all settings from database
            $settings = self::all()->pluck('value', 'key')->toArray();
            
            // Create config file content
            $configContent = "<?php\n\nreturn " . var_export($settings, true) . ";\n";
            
            // Write to config file
            $configPath = config_path('site.php');
            File::put($configPath, $configContent);
            
            // Clear config cache
            Artisan::call('config:clear');
            
            // Optionally cache config for production
            if (app()->environment('production')) {
                Artisan::call('config:cache');
            }
            
        } catch (\Exception $e) {
            \Log::error('Failed to refresh settings cache: ' . $e->getMessage());
        }
    }

    // Scopes
    public function scopeByGroup($query, $group)
    {
        return $query->where('group', $group);
    }

    public function scopeByType($query, $type)
    {
        return $query->where('type', $type);
    }
}
