<?php

namespace App\Models;

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

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

    protected static function booted(): void
    {
        static::saved(fn () => Cache::forget('settings.all'));
        static::deleted(fn () => Cache::forget('settings.all'));
    }

    public static function all_cached(): array
    {
        return Cache::remember('settings.all', 600, function () {
            return static::query()->pluck('value', 'key')->all();
        });
    }

    public static function get(string $key, ?string $default = null): ?string
    {
        return static::all_cached()[$key] ?? $default;
    }

    public static function set(string $key, ?string $value): void
    {
        static::updateOrCreate(['key' => $key], ['value' => $value]);
    }

    public static function logoUrl(): ?string
    {
        $path = static::get('logo_path');
        return $path ? Storage::url($path) : null;
    }

    public static function faviconUrl(): ?string
    {
        $path = static::get('favicon_path');
        return $path ? Storage::url($path) : null;
    }

    /**
     * Konfigurasi mitra OKE Laundry (dengan fallback default).
     */
    public static function mitra(): array
    {
        return [
            'name' => static::get('mitra_name', 'OKE Laundry'),
            'address' => static::get('mitra_address', 'Jl. Poin Mas, Mampang, Pancoran Mas, Kota Depok, Jawa Barat 16433'),
            'phone' => static::get('mitra_phone', ''),
            'hours' => static::get('mitra_hours', 'Setiap hari, 08.00 - 18.00 WIB'),
            'lat' => (float) static::get('mitra_lat', '-6.39778'),
            'lng' => (float) static::get('mitra_lng', '106.79769'),
            'cost_per_km' => (int) static::get('mitra_cost_per_km', '3500'),
            'free_radius_km' => (float) static::get('mitra_free_radius_km', '2'),
        ];
    }
}
