<?php

namespace Modules\MedBloodBank\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * A collected blood bag (SIFA P6-T6). Spec-level inventory: the bag lives here,
 * never auto-mirrored as an ERP product. `screening` is the JSON marker panel
 * (hiv/hbv/hcv/syphilis => negative|reactive|pending). expiry_date is derived by
 * BloodBankService::expiryFor().
 */
class MbbDonation extends Model
{
    protected $table = 'mbb_donations';

    protected $guarded = ['id'];

    protected $casts = [
        'screening'    => 'array',
        'volume_ml'    => 'integer',
        'collected_at' => 'datetime',
        'expiry_date'  => 'date',
    ];

    public const BLOOD_GROUPS   = ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-'];
    public const DONATION_TYPES = ['voluntary', 'replacement', 'autologous', 'apheresis'];
    public const PRODUCT_TYPES  = ['whole_blood', 'prbc', 'ffp', 'platelets', 'cryo'];
    public const SCREENING_MARKERS = ['hiv', 'hbv', 'hcv', 'syphilis'];

    /** Full bag lifecycle. */
    public const STATUSES = [
        'collected', 'quarantined', 'available', 'reserved',
        'issued', 'transfused', 'expired', 'discarded',
    ];

    public function donor()
    {
        return $this->belongsTo(MbbDonor::class, 'donor_id');
    }

    public function crossmatches()
    {
        return $this->hasMany(MbbCrossmatch::class, 'donation_id');
    }

    public function issues()
    {
        return $this->hasMany(MbbIssue::class, 'donation_id');
    }

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

    public function scopeAvailable($query)
    {
        return $query->where('status', 'available');
    }

    /** A bag is issuable only while it is available and not past expiry. */
    public function isIssuable(): bool
    {
        return $this->status === 'available'
            && (! $this->expiry_date || ! $this->expiry_date->isPast());
    }
}
