<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Brand extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'slug',
        'domain',
        'reseller_id',
        'logo',
        'favicon',
        'theme',
        'primary_color',
        'secondary_color',
        'footer_text',
        'contact_email',
        'contact_phone',
        'visible_product_groups',
        'visible_tlds',
        'domain_verification_token',
        'domain_verified',
        'domain_verified_at',
        'default_language',
        'default_currency',
        'settings',
        'email_settings',
        'seo_overrides',
        'custom_css',
        'custom_js',
        'is_default',
        'is_active',
    ];

    protected $casts = [
        'settings' => 'array',
        'email_settings' => 'array',
        'seo_overrides' => 'array',
        'visible_product_groups' => 'array',
        'visible_tlds' => 'array',
        'domain_verified' => 'boolean',
        'domain_verified_at' => 'datetime',
        'is_default' => 'boolean',
        'is_active' => 'boolean',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($brand) {
            if (empty($brand->slug)) {
                $brand->slug = Str::slug($brand->name);
            }
        });
    }

    public function reseller()
    {
        return $this->belongsTo(Reseller::class);
    }

    public function clients()
    {
        return $this->hasMany(Client::class);
    }

    public function orders()
    {
        return $this->hasMany(Order::class);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeDefault($query)
    {
        return $query->where('is_default', true);
    }

    /**
     * Resolve brand from request domain.
     */
    public static function resolveFromRequest(): ?self
    {
        $host = request()->getHost();

        return static::where('domain', $host)->active()->first()
            ?? static::default()->first();
    }

    /**
     * Get a setting value with fallback to global settings.
     */
    public function getSetting(string $key, $default = null)
    {
        return data_get($this->settings, $key, Setting::getValue($key, $default));
    }
}
