<?php

namespace App\Models\Warehouse;

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

class LpoItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'lpo_id',
        'item_id',
        'quantity_ordered',
        'quantity_delivered',
        'quantity_remaining',
        'unit_of_measure',
        'unit_price',
        'total_price',
        'currency',
        'expected_delivery_date',
        'status',
        'specifications',
        'notes'
    ];

    protected $casts = [
        'quantity_ordered' => 'decimal:2',
        'quantity_delivered' => 'decimal:2',
        'quantity_remaining' => 'decimal:2',
        'unit_price' => 'decimal:2',
        'total_price' => 'decimal:2',
        'expected_delivery_date' => 'date',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * Boot the model
     */
    protected static function boot()
    {
        parent::boot();

        static::saving(function ($item) {
            // Auto-calculate total price
            $item->total_price = $item->quantity_ordered * $item->unit_price;

            // Calculate remaining quantity
            $item->quantity_remaining = $item->quantity_ordered - $item->quantity_delivered;

            // Update status based on delivery
            if ($item->quantity_delivered >= $item->quantity_ordered) {
                $item->status = 'fully_delivered';
            } elseif ($item->quantity_delivered > 0) {
                $item->status = 'partially_delivered';
            } else {
                $item->status = 'pending';
            }
        });
    }

    /**
     * Get the LPO
     */
    public function lpo(): BelongsTo
    {
        return $this->belongsTo(LpoManagement::class, 'lpo_id');
    }

    /**
     * Get the item details
     */
    public function item(): BelongsTo
    {
        return $this->belongsTo(Item::class);
    }

    /**
     * Check if item is fully delivered
     */
    public function isFullyDelivered()
    {
        return $this->quantity_delivered >= $this->quantity_ordered;
    }

    /**
     * Check if item is partially delivered
     */
    public function isPartiallyDelivered()
    {
        return $this->quantity_delivered > 0 && $this->quantity_delivered < $this->quantity_ordered;
    }

    /**
     * Check if item delivery is overdue
     */
    public function isOverdue()
    {
        return $this->expected_delivery_date &&
               $this->expected_delivery_date < now() &&
               !$this->isFullyDelivered();
    }

    /**
     * Get delivery percentage
     */
    public function getDeliveryPercentageAttribute()
    {
        if ($this->quantity_ordered == 0) {
            return 0;
        }

        return ($this->quantity_delivered / $this->quantity_ordered) * 100;
    }

    /**
     * Get status badge class
     */
    public function getStatusBadgeClassAttribute()
    {
        return match($this->status) {
            'pending' => 'badge-warning',
            'partially_delivered' => 'badge-info',
            'fully_delivered' => 'badge-success',
            'cancelled' => 'badge-danger',
            default => 'badge-secondary'
        };
    }

    /**
     * Get formatted unit price
     */
    public function getFormattedUnitPriceAttribute()
    {
        return $this->currency . ' ' . number_format($this->unit_price, 2);
    }

    /**
     * Get formatted total price
     */
    public function getFormattedTotalPriceAttribute()
    {
        return $this->currency . ' ' . number_format($this->total_price, 2);
    }

    /**
     * Update delivery quantity
     */
    public function updateDelivery($deliveredQuantity)
    {
        $this->quantity_delivered += $deliveredQuantity;
        $this->save();

        // Update parent LPO delivery status
        $this->lpo->updateDeliveryStatus();
    }
}