<?php

namespace App\Models;

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

class Dealer extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $fillable = [
        'name',
        'domain',
        'business_registration_number',
        'vat_number',
        'address',
        'telephone',
        'contact_email',
        'main_contact_name',
        'main_contact_cell',
        'main_contact_email',
        'is_active',
        'provisioning_status',
        'logo_path',
        'favicon_path',
        'nav_color',
        'accent_color',
        'accent_color_2',
        'background_color',
        'topbar_color',
        'login_background_path',
        'login_logo_path',
        'login_accent_color',
    ];

    protected $casts = [
        'is_default' => 'bool',
        'is_active' => 'bool',
        'provisioned_at' => 'datetime',
        'baseline_last_applied_at' => 'datetime',
    ];

    public function loginBackgroundUrl(): string
    {
        if (is_string($this->login_background_path) && trim($this->login_background_path) !== '') {
            return asset('storage/'.$this->login_background_path);
        }

        // Platform default login background (current Mega Theron tire-track image).
        return asset('images/login-bg.svg');
    }

    public function loginLogoUrl(): string
    {
        if (is_string($this->login_logo_path) && trim($this->login_logo_path) !== '') {
            return asset('storage/'.$this->login_logo_path);
        }

        if (is_string($this->logo_path) && trim($this->logo_path) !== '') {
            return asset('storage/'.$this->logo_path);
        }

        // Fallback to the existing main Mega Theron logo.
        return asset('images/mega-theron-logo.png');
    }

    public function loginEffectiveAccentColor(): string
    {
        if (is_string($this->login_accent_color) && trim($this->login_accent_color) !== '') {
            return trim($this->login_accent_color);
        }

        if (is_string($this->accent_color) && trim($this->accent_color) !== '') {
            return trim($this->accent_color);
        }

        // Default to Tailwind red-600 used historically.
        return '#dc2626';
    }

    public function departments(): HasMany
    {
        return $this->hasMany(Department::class);
    }

    public function provisioningRuns(): HasMany
    {
        return $this->hasMany(DealerProvisioningRun::class);
    }

    public function branches(): HasMany
    {
        return $this->hasMany(Branch::class);
    }

    public function documents(): HasMany
    {
        return $this->hasMany(DealerDocument::class);
    }
}
