<?php

namespace App\Models\Warehouse;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class MaterialSiteTransfer extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'from_project_id',
        'to_project_id',
        'transfer_date',
        'notes',
        'transferred_by',
        'status',
        'total_value'
    ];

    protected $casts = [
        'transfer_date' => 'date',
        'total_value' => 'decimal:2'
    ];

    /**
     * Get the project that materials are transferred from.
     */
    public function fromProject(): BelongsTo
    {
        return $this->belongsTo(Project::class, 'from_project_id');
    }

    /**
     * Get the project that materials are transferred to.
     */
    public function toProject(): BelongsTo
    {
        return $this->belongsTo(Project::class, 'to_project_id');
    }

    /**
     * Get the user who performed the transfer.
     */
    public function transferredBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'transferred_by');
    }

    /**
     * Get the items in this transfer.
     */
    public function items(): HasMany
    {
        return $this->hasMany(MaterialSiteTransferItem::class, 'site_transfer_id');
    }

    /**
     * Get the transfer number formatted.
     */
    public function getTransferNumberAttribute()
    {
        return 'ST-' . str_pad($this->id, 5, '0', STR_PAD_LEFT);
    }
}