<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Company extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'name',
        'email',
        'phone',
        'address',
        'city',
        'state',
        'zip',
        'country',
        'logo',
        'tax_id',
        'registration_number',
        'website',
        'is_active',
    ];

    protected $casts = [
        'is_active' => 'boolean',
    ];

    /**
     * Get the logo URL
     */
    public function getLogoUrlAttribute(): ?string
    {
        if (! $this->logo) {
            return null;
        }

        if (filter_var($this->logo, FILTER_VALIDATE_URL)) {
            return $this->logo;
        }

        if (\Illuminate\Support\Facades\Storage::disk('public')->exists($this->logo)) {
            // Use asset() helper which uses the current request's domain
            return asset('storage/'.$this->logo);
        }

        return null;
    }

    /**
     * Normalize company name for matching settings vs `companies` (spacing, case, trailing punctuation).
     */
    public static function normalizeBillFromNameKey(string $name): string
    {
        $n = Str::lower(trim(preg_replace('/\s+/', ' ', $name)));

        return rtrim($n, ". \t\n\r\0\x0B");
    }

    /**
     * Match a row in `companies` to company_settings (Bill From), create one from settings if needed,
     * or fall back to first active / any company.
     */
    public static function resolveBillFromCompany(): ?self
    {
        $settings = CompanySetting::getSettings();
        $name = trim((string) ($settings->company_name ?? ''));

        if ($name !== '') {
            $exact = static::query()->where('name', $name)->first();
            if ($exact !== null) {
                return $exact;
            }

            $lower = Str::lower($name);
            $ci = static::query()->whereRaw('LOWER(name) = ?', [$lower])->first();
            if ($ci !== null) {
                return $ci;
            }

            $key = static::normalizeBillFromNameKey($name);
            foreach (static::query()->orderBy('id')->get() as $row) {
                if (static::normalizeBillFromNameKey((string) $row->name) === $key) {
                    return $row;
                }
            }

            return static::query()->create([
                'name' => $name,
                'email' => $settings->company_email,
                'phone' => $settings->company_phone,
                'address' => $settings->company_address,
                'city' => $settings->company_city,
                'state' => $settings->company_state,
                'zip' => $settings->company_zip,
                'country' => $settings->company_country,
                'tax_id' => $settings->company_tax_id,
                'registration_number' => $settings->company_registration_number,
                'logo' => $settings->company_logo,
                'is_active' => true,
            ]);
        }

        return static::query()->where('is_active', true)->orderBy('id')->first()
            ?? static::query()->orderBy('id')->first();
    }
}
