<?php

namespace Modules\MedBloodBank\Entities;

use App\Contact;
use Illuminate\Database\Eloquent\Model;

/**
 * A donor (SIFA P6-T6). A donor IS an ERP contact (type customer/both) with this
 * satellite carrying the donor-specific fields — never a parallel person table.
 * `contact()` is the canonical accessor for the donor person.
 */
class MbbDonor extends Model
{
    protected $table = 'mbb_donors';

    protected $guarded = ['id'];

    protected $casts = [
        'last_donation_at' => 'datetime',
        'deferred_until'   => 'date',
        'total_donations'  => 'integer',
    ];

    public const BLOOD_GROUPS = ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-'];

    public function contact()
    {
        return $this->belongsTo(Contact::class, 'contact_id');
    }

    public function donations()
    {
        return $this->hasMany(MbbDonation::class, 'donor_id');
    }

    public function scopeForBusiness($query, $businessId)
    {
        return $query->where('business_id', $businessId);
    }

    /** Convenience: the donor's display name via the linked ERP contact. */
    public function getDisplayNameAttribute(): string
    {
        $c = $this->contact;
        if (! $c) {
            return '#' . $this->contact_id;
        }

        return trim($c->name ?? '') ?: trim($c->supplier_business_name ?? '') ?: ('#' . $this->contact_id);
    }
}
