<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    use HasFactory;

    protected $fillable = [
        'key',
        'value',
    ];

    public static function get(string $key, $default = null)
    {
        try {
            return \Illuminate\Support\Facades\Cache::remember("setting.{$key}", 3600, function () use ($key, $default) {
                $setting = static::where('key', $key)->first();
                return $setting ? $setting->value : $default;
            });
        } catch (\Exception $e) {
            // Fallback if cache is not available
            $setting = static::where('key', $key)->first();
            return $setting ? $setting->value : $default;
        }
    }

    public static function set(string $key, $value): void
    {
        static::updateOrCreate(['key' => $key], ['value' => $value]);
        
        // Clear cache for this setting
        try {
            \Illuminate\Support\Facades\Cache::forget("setting.{$key}");
        } catch (\Exception $e) {
            // Ignore cache errors
        }
    }

    /**
     * Get logo URL with fallback to default
     * 
     * @param string $type 'light' or 'dark'
     * @return string|null
     */
    public static function getLogoUrl(string $type = 'light'): ?string
    {
        $logoKey = $type === 'dark' ? 'site_logo_dark' : 'site_logo';
        $logoPath = static::get($logoKey);
        
        if ($logoPath && \Illuminate\Support\Facades\Storage::disk('public')->exists($logoPath)) {
            return asset('storage/' . $logoPath);
        }
        
        // Fallback to default logo
        $defaultPath = 'images/logo.png';
        if ($type === 'dark') {
            $defaultPath = 'images/logo-dark.png';
        }
        
        // Check if default exists
        if (file_exists(public_path($defaultPath))) {
            return asset($defaultPath);
        }
        
        return null; // Return null if no logo available
    }

    /**
     * Check if logo exists
     * 
     * @param string $type 'light' or 'dark'
     * @return bool
     */
    public static function hasLogo(string $type = 'light'): bool
    {
        $logoKey = $type === 'dark' ? 'site_logo_dark' : 'site_logo';
        $logoPath = static::get($logoKey);
        
        return $logoPath && \Illuminate\Support\Facades\Storage::disk('public')->exists($logoPath);
    }
}
