<?php

namespace App\Support;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class AppSettings
{
    public static function get(string $key, mixed $default = null, ?int $branchId = null): mixed
    {
        $settings = self::all($branchId);

        return $settings[$key] ?? $default;
    }

    public static function all(?int $branchId = null): array
    {
        return Cache::remember("app-settings.{$branchId}", 60, function () use ($branchId): array {
            $global = DB::table('app_settings')->whereNull('branch_id')->pluck('value', 'key')->all();
            $branch = $branchId
                ? DB::table('app_settings')->where('branch_id', $branchId)->pluck('value', 'key')->all()
                : [];

            return collect($global)
                ->merge($branch)
                ->map(fn ($value) => json_decode($value, true) ?? $value)
                ->all();
        });
    }

    public static function businessName(?int $branchId = null): string
    {
        return (string) self::get('business_name', config('app.name', 'POS Laundry'), $branchId);
    }

    public static function logoUrl(?int $branchId = null): ?string
    {
        $path = self::get('business_logo', null, $branchId);

        return $path ? '/storage/'.ltrim($path, '/') : null;
    }

    public static function clear(): void
    {
        Cache::flush();
    }
}
