<?php

namespace App\Models;

use App\Models\BaseModel;
use App\Scopes\CompanyScope;

class SelfConfiguration extends BaseModel
{
    protected $table = 'self_configurations';

    protected $default = ['xid', 'group_name', 'config_key', 'config_value'];

    protected $guarded = ['id', 'created_at', 'updated_at'];

    protected $hidden = ['id', 'company_id'];

    protected $appends = ['xid', 'x_company_id'];
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new CompanyScope);
    }


    /**
     * Scope: filter by group
     */
    public function scopeGroup($query, string $group)
    {
        return $query->where('group_name', $group);
    }

    /**
     * Scope: filter by company
     */
    public function scopeCompany($query, $companyId)
    {
        return $query->where('company_id', $companyId);
    }

    /**
     * Get config value by key
     */
    public static function getValue(
        string $group,
        string $key,
        $companyId = null,
        $default = 0
    ) {
        return self::where('group_name', $group)
            ->where('config_key', $key)
            ->when($companyId, fn ($q) => $q->where('company_id', $companyId))
            ->value('config_value') ?? $default;
    }
    /**
     * Set or update config value
     */
    public static function setValue(
        string $group,
        string $key,
        int $value,
        $companyId = null
    ): self {
        // Use the passed companyId or get from company() helper
        if ($companyId === null) {
            $companyId = company()->id;
        }
    
        return self::updateOrCreate(
            [
                'group_name' => $group,
                'config_key' => $key,
                'company_id' => $companyId,
            ],
            [
                'config_value' => $value,
            ]
        );
    }
}
