<?php

namespace App\Models;

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

class PurchaseItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'purchase_id',
        'product_id',
        'product_code',
        'product_name',
        'quantity',
        'received_quantity',
        'pending_quantity',
        'unit_cost',
        'unit_price',
        'tax_rate',
        'discount_rate',
        'total_cost',
        'expiry_date',
        'batch_no',
        'status'
    ];

    protected $casts = [
        'quantity' => 'decimal:2',
        'received_quantity' => 'decimal:2',
        'pending_quantity' => 'decimal:2',
        'unit_cost' => 'decimal:2',
        'unit_price' => 'decimal:2',
        'total_cost' => 'decimal:2',
        'expiry_date' => 'date'
    ];

    // Relationships
    public function purchase(): BelongsTo
    {
        return $this->belongsTo(Purchase::class);
    }

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

    // Accessors
    public function getStatusTextAttribute()
    {
        $statuses = [
            'pending' => 'Pending',
            'received' => 'Received',
            'partial' => 'Partial',
            'cancelled' => 'Cancelled'
        ];
        
        return $statuses[$this->status] ?? 'Unknown';
    }

    public function getStatusColorAttribute()
    {
        $colors = [
            'pending' => 'warning',
            'received' => 'success',
            'partial' => 'info',
            'cancelled' => 'danger'
        ];
        
        return $colors[$this->status] ?? 'secondary';
    }

    // Methods
    public function updateReceivedQuantity($quantity)
    {
        $newReceived = $this->received_quantity + $quantity;
        $newPending = max(0, $this->quantity - $newReceived);
        
        $this->update([
            'received_quantity' => $newReceived,
            'pending_quantity' => $newPending,
            'status' => $newPending > 0 ? 'partial' : 'received'
        ]);
    }

    public function updateProductStock()
    {
        if ($this->product && $this->status == 'received') {
            $this->product->increment('stock_quantity', $this->received_quantity);
            $this->product->update(['cost_price' => $this->unit_cost]);
        }
    }

    // Scopes
    public function scopeByProduct($query, $productId)
    {
        return $query->where('product_id', $productId);
    }

    public function scopeByPurchase($query, $purchaseId)
    {
        return $query->where('purchase_id', $purchaseId);
    }

    public function scopePending($query)
    {
        return $query->whereIn('status', ['pending', 'partial']);
    }

    public function scopeReceived($query)
    {
        return $query->where('status', 'received');
    }
}