<?php

namespace App\Models;

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

class Supplier extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'farm_id', 'name', 'nickname', 'business_name',
        'address', 'landmark', 'email', 'phone', 'whatsapp',
        'notes', 'is_flagged', 'flag_reason',
    ];

    protected function casts(): array
    {
        return [
            'is_flagged' => 'boolean',
        ];
    }

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

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

    public function receipts(): HasMany
    {
        return $this->hasMany(InventoryMovement::class)->where('movement_type', 'receipt');
    }

    /** WhatsApp deep-link number (E.164 digits, Nigerian 0x → 234x). */
    public function getWaNumberAttribute(): ?string
    {
        $raw = $this->whatsapp ?? $this->phone;
        if (! $raw) {
            return null;
        }

        $digits = preg_replace('/\D/', '', $raw);

        if (str_starts_with($digits, '0')) {
            $digits = '234'.substr($digits, 1);
        }

        return $digits ?: null;
    }

    public function getDisplayNameAttribute(): string
    {
        if ($this->business_name) {
            return $this->business_name.($this->nickname ? " ({$this->nickname})" : '');
        }

        return $this->name.($this->nickname ? " ({$this->nickname})" : '');
    }
}
