<?php

namespace App\Models;

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

class SchoolSetting extends Model
{
    protected $fillable = ['key', 'value'];

    /**
     * Cache key prefix for school settings
     */
    private const CACHE_KEY = 'school_settings_all';
    private const CACHE_TTL = 3600; // 1 hour

    /**
     * Get a setting value by key, with optional default
     */
    public static function get(string $key, ?string $default = null): ?string
    {
        $settings = static::getAllCached();
        return $settings[$key] ?? $default;
    }

    /**
     * Set a setting value by key
     */
    public static function set(string $key, ?string $value): void
    {
        static::updateOrCreate(['key' => $key], ['value' => $value]);
        static::clearCache();
    }

    /**
     * Get all settings as key-value array, cached
     */
    public static function getAllCached(): array
    {
        return Cache::remember(static::CACHE_KEY, static::CACHE_TTL, function () {
            return static::pluck('value', 'key')->toArray();
        });
    }

    /**
     * Clear the settings cache
     */
    public static function clearCache(): void
    {
        Cache::forget(static::CACHE_KEY);
    }

    /**
     * Get the public URL for a file setting (logo, favicon, signature)
     */
    public static function getFileUrl(string $key): ?string
    {
        $path = static::get($key);
        if (empty($path)) {
            return null;
        }
        return asset('storage/' . $path);
    }
}
