<?php

namespace App\Models;

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

class Setting extends Model
{
    use HasFactory;

    protected $fillable = ['group', 'key', 'value'];

    // Default configuration for modules
    public const MODULES = [
        'module_crm' => true,
        'module_accounting' => true,
        'module_hr' => false,
        'module_inventory' => false, // Default false as per request
        'module_projects' => true,
        'module_quotations' => true,
        'module_subscriptions' => true,
        'module_ai' => true,
    ];

    /**
     * Check if a module is enabled.
     * Uses Cache to prevent frequent DB queries.
     */
    public static function isModuleEnabled($key)
    {
        // Use the same logic as getValue for consistency
        return self::getValue('modules', $key, self::MODULES[$key] ?? false) == '1' || self::getValue('modules', $key, self::MODULES[$key] ?? false) === true;
    }

    public static function getValue($group, $key, $default = null)
    {
        return Cache::rememberForever("setting_{$group}_{$key}", function () use ($group, $key, $default) {
            $setting = self::where('group', $group)->where('key', $key)->first();
            return $setting ? $setting->value : $default;
        });
    }

    public static function setValue($group, $key, $value)
    {
        $setting = self::updateOrCreate(
            ['group' => $group, 'key' => $key],
            ['value' => $value]
        );
        Cache::forget("setting_{$group}_{$key}");
        return $setting;
    }

    public static function getGroup($group)
    {
        return self::where('group', $group)->pluck('value', 'key')->toArray();
    }

    public static function setGroup($group, array $values)
    {
        foreach ($values as $key => $value) {
            self::setValue($group, $key, $value);
        }
    }

    /**
     * Clear settings cache
     */
    protected static function boot()
    {
        parent::boot();

        static::saved(function ($setting) {
            Cache::forget("setting_{$setting->key}");
            Cache::forget("setting_{$setting->group}_{$setting->key}");
            Cache::forget('app_settings');
        });

        static::deleted(function ($setting) {
            Cache::forget("setting_{$setting->key}");
            Cache::forget("setting_{$setting->group}_{$setting->key}");
            Cache::forget('app_settings');
        });
    }
}
