<?php

namespace App\Models;

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

class SystemPreference extends Model
{
    use HasFactory;

    protected $fillable = [
        'school_id',
        'preference_key',
        'preference_value',
        'preference_type',
        'description',
        'is_editable',
    ];

    protected $casts = [
        'preference_value' => 'array',
        'is_editable' => 'boolean',
    ];

    // Relationships
    public function school()
    {
        return $this->belongsTo(School::class);
    }

    // Scopes
    public function scopeForSchool($query, $schoolId)
    {
        return $query->where('school_id', $schoolId);
    }

    public function scopeEditable($query)
    {
        return $query->where('is_editable', true);
    }

    public function scopeByKey($query, $key)
    {
        return $query->where('preference_key', $key);
    }

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

    // Methods
    public static function getValue($key, $schoolId = null)
    {
        $query = static::where('preference_key', $key);

        if ($schoolId) {
            $query->where('school_id', $schoolId);
        }

        $preference = $query->first();

        return $preference ? $preference->preference_value : null;
    }

    public static function setValue($key, $value, $schoolId = null)
    {
        return static::updateOrCreate(
            [
                'preference_key' => $key,
                'school_id' => $schoolId,
            ],
            [
                'preference_value' => $value,
            ]
        );
    }
}
