<?php

namespace App\Models\Warehouse;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class MaterialTransferIssueItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'transfer_issue_id',
        'transfer_request_item_id',
        'item_id',
        'quantity_requested',
        'quantity_issued',
        'quantity_received',
        'quantity_rejected',
        'unit_of_measure',
        'unit_price',
        'total_value',
        'batch_number',
        'serial_numbers',
        'manufacturing_date',
        'expiry_date',
        'source_location',
        'source_notes',
        'condition',
        'condition_notes',
        'receipt_status',
        'receipt_notes'
    ];

    protected $casts = [
        'quantity_requested' => 'decimal:2',
        'quantity_issued' => 'decimal:2',
        'quantity_received' => 'decimal:2',
        'quantity_rejected' => 'decimal:2',
        'unit_price' => 'decimal:2',
        'total_value' => 'decimal:2',
        'manufacturing_date' => 'date',
        'expiry_date' => 'date'
    ];

    protected static function boot()
    {
        parent::boot();

        static::saving(function ($issueItem) {
            // Auto-calculate total value
            $issueItem->total_value = $issueItem->quantity_issued * $issueItem->unit_price;
        });
    }

    /**
     * Relationships
     */
    public function transferIssue(): BelongsTo
    {
        return $this->belongsTo(MaterialTransferIssue::class, 'transfer_issue_id');
    }

    public function transferRequestItem(): BelongsTo
    {
        return $this->belongsTo(MaterialTransferRequestItem::class, 'transfer_request_item_id');
    }

    public function item(): BelongsTo
    {
        return $this->belongsTo(Item::class);
    }

    /**
     * Receipt Management
     */
    public function receiveQuantity($quantity, $notes = null, $condition = 'good')
    {
        $this->quantity_received += $quantity;
        $this->receipt_notes = $notes;
        $this->condition = $condition;

        // Update receipt status based on quantities
        if ($this->quantity_received >= $this->quantity_issued) {
            $this->receipt_status = 'received';
        } elseif ($this->quantity_received > 0) {
            $this->receipt_status = 'partial';
        }

        $this->save();
    }

    public function rejectQuantity($quantity, $notes = null)
    {
        $this->quantity_rejected += $quantity;
        $this->receipt_notes = $notes;
        $this->receipt_status = $this->quantity_rejected >= $this->quantity_issued ? 'rejected' : 'partial';
        $this->save();
    }

    public function markDamaged($notes = null)
    {
        $this->receipt_status = 'damaged';
        $this->receipt_notes = $notes;
        $this->condition = 'poor';
        $this->save();
    }

    /**
     * Status Checks
     */
    public function isFullyReceived()
    {
        return $this->quantity_received >= $this->quantity_issued;
    }

    public function isPartiallyReceived()
    {
        return $this->quantity_received > 0 && $this->quantity_received < $this->quantity_issued;
    }

    public function isPending()
    {
        return $this->receipt_status === 'pending';
    }

    public function isRejected()
    {
        return $this->receipt_status === 'rejected';
    }

    public function isDamaged()
    {
        return $this->receipt_status === 'damaged';
    }

    /**
     * Quantity Calculations
     */
    public function getQuantityPendingAttribute()
    {
        return $this->quantity_issued - $this->quantity_received - $this->quantity_rejected;
    }

    public function getReceiptPercentageAttribute()
    {
        if ($this->quantity_issued <= 0) return 0;
        return round(($this->quantity_received / $this->quantity_issued) * 100, 2);
    }

    /**
     * Quality Checks
     */
    public function isExpired()
    {
        return $this->expiry_date && $this->expiry_date < now();
    }

    public function isExpiringSoon($days = 30)
    {
        return $this->expiry_date &&
               $this->expiry_date > now() &&
               $this->expiry_date <= now()->addDays($days);
    }

    /**
     * Get receipt status badge color
     */
    public function getReceiptStatusColorAttribute()
    {
        return match($this->receipt_status) {
            'pending' => 'warning',
            'received' => 'success',
            'partial' => 'info',
            'rejected' => 'danger',
            'damaged' => 'dark',
            default => 'secondary'
        };
    }

    /**
     * Get condition badge color
     */
    public function getConditionColorAttribute()
    {
        return match($this->condition) {
            'new' => 'success',
            'good' => 'info',
            'fair' => 'warning',
            'poor' => 'danger',
            default => 'secondary'
        };
    }
}