<?php

namespace App\Models\BloodBank;

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

class BloodDonation extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'blood_bank_id',
        'request_id',
        'blood_type',
        'units',
        'donation_date',
        'status',
        'notes'
    ];

    protected $casts = [
        'donation_date' => 'date'
    ];

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

    public function bloodBank()
    {
        return $this->belongsTo(BloodBank::class);
    }

    public function request()
    {
        return $this->belongsTo(BloodRequest::class, 'request_id');
    }

    // Update user's donation info when donation is completed
    public function updateUserDonationInfo()
    {
        if ($this->status === 'completed') {
            $user = $this->user;
            $user->last_donation_date = $this->donation_date;
            $user->donation_count += 1;
            $user->is_donor = true;
            $user->save();

            // If donation is for a blood bank, update inventory
            if ($this->blood_bank_id) {
                $inventory = BloodInventory::firstOrNew([
                    'blood_bank_id' => $this->blood_bank_id,
                    'blood_type' => $this->blood_type
                ]);
                
                $inventory->units_available = ($inventory->units_available ?? 0) + $this->units;
                $inventory->save();
                $inventory->updateStockStatus();
            }

            // If donation is for a request, update request fulfillment
            if ($this->request_id) {
                $this->request->updateFulfillmentStatus();
            }
        }
    }
}
