<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Company extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'company_code','name','legal_name','email','phone',
        'address','city','country','tax_id','logo','website','status',
        'company_group_id',
    ];

    protected $casts = ['status' => 'string'];

    public function group()
    {
        return $this->belongsTo(CompanyGroup::class, 'company_group_id');
    }

    public function subscription()
    {
        return $this->hasOne(CompanySubscription::class);
    }

    public function users()
    {
        return $this->hasMany(User::class);
    }

    public function admin()
    {
        return $this->hasOne(User::class)->where('is_admin', true);
    }

    public function settings()
    {
        return $this->hasMany(Setting::class);
    }

    public function getSetting(string $key, $default = null)
    {
        return $this->settings()->where('key', $key)->value('value') ?? $default;
    }

    public function getLogoUrlAttribute(): ?string
    {
        return app(\App\Support\BrandLogoManager::class)->companyLogoUrl($this);
    }

    public function hasLogo(): bool
    {
        return filled($this->logo)
            && \Illuminate\Support\Facades\Storage::disk('public')->exists($this->logo);
    }

    public function isActive(): bool
    {
        return $this->status === 'active';
    }
}
