<?php

namespace App\Models;

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

class SiteSetting extends Model
{
    use HasFactory;

    protected $table = 'site_settings';
    
    protected $fillable = [
        'setting_key',
        'setting_value',
        'language_code',
        'description',
        'is_active'
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'setting_value' => 'json'
    ];

    public function language()
    {
        return $this->belongsTo(Language::class, 'language_code', 'code');
    }

    public static function getSetting($key, $languageCode = null)
    {
        if (!$languageCode) {
            $languageCode = app()->getLocale();
        }

        $setting = self::where('setting_key', $key)
            ->where('language_code', $languageCode)
            ->where('is_active', 1)
            ->first();

        return $setting ? $setting->setting_value : null;
    }

    public static function setSetting($key, $value, $languageCode = null, $description = null)
    {
        if (!$languageCode) {
            $languageCode = app()->getLocale();
        }

        return self::updateOrCreate(
            [
                'setting_key' => $key,
                'language_code' => $languageCode
            ],
            [
                'setting_value' => $value,
                'description' => $description,
                'is_active' => true
            ]
        );
    }
} 