<?php
namespace App\Models\BloodBank;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class BloodRequest extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'blood_type',
        'units_needed',
        'hospital_id',
        'hospital_name',
        'hospital_address',
        'contact_phone',
        'reason',
        'urgency',
        'status',
        'units_fulfilled',
        'needed_by',
        'is_public',
        'latitude',
        'longitude'
    ];

    protected $casts = [
        'needed_by' => 'date',
        'is_public' => 'boolean'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function hospital()
    {
        return $this->belongsTo(BloodBank::class, 'hospital_id');
    }

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

    // Check if request is fully fulfilled
    public function updateFulfillmentStatus()
    {
        $this->units_fulfilled = $this->donations()
            ->where('status', 'completed')
            ->sum('units');

        if ($this->units_fulfilled >= $this->units_needed) {
            $this->status = 'fulfilled';
        } elseif ($this->units_fulfilled > 0) {
            $this->status = 'partially_fulfilled';
        }
        
        $this->save();
    }
}
