<?php

namespace App\Services;

use App\Models\CmsSetting;
use Illuminate\Support\Facades\Cache;

class CmsService
{
    /**
     * Get a CMS setting by key.
     */
    public function get(string $key, $default = null)
    {
        return Cache::rememberForever("cms_setting_{$key}", function () use ($key, $default) {
            $setting = CmsSetting::where('key', $key)->first();
            return $setting ? $setting->value : $default;
        });
    }

    /**
     * Set/Update a CMS setting.
     */
    public function set(string $key, $value, string $type = 'text', string $group = 'landing')
    {
        CmsSetting::updateOrCreate(
            ['key' => $key],
            ['value' => $value, 'type' => $type, 'group' => $group]
        );
        
        Cache::forget("cms_setting_{$key}");
    }

    /**
     * Get multiple settings at once.
     */
    public function getMany(array $keys): array
    {
        $settings = [];
        foreach ($keys as $key) {
            $settings[$key] = $this->get($key);
        }
        return $settings;
    }

    /**
     * Get all settings for landing page.
     */
    public function getLandingSettings(): array
    {
        return Cache::rememberForever('cms_landing_settings', function () {
            return CmsSetting::where('group', 'landing')->pluck('value', 'key')->toArray();
        });
    }

    /**
     * Clear all CMS cache.
     */
    public function clearCache()
    {
        CmsSetting::all()->each(function ($setting) {
            Cache::forget("cms_setting_{$setting->key}");
        });
        Cache::forget('cms_landing_settings');
    }

    /**
     * Get all settings grouped (for admin form).
     */
    public function getAllGrouped(): array
    {
        return CmsSetting::all()->pluck('value', 'key')->toArray();
    }
}
