<?php

namespace Modules\PurchaseRequisition\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class PrProduct extends Model
{
    use SoftDeletes;

    protected $table = 'pr_products';

    protected $guarded = ['id'];

    protected $casts = [
        'current_stock' => 'decimal:4',
        'required_quantity' => 'decimal:4',
        'covered_qty' => 'decimal:4',
        'pending_purchase_qty' => 'decimal:4',
        'avg_unit_cost' => 'decimal:4',
        'last_purchase_price' => 'decimal:4',
        'last_purchased_qty' => 'decimal:4',
        'last_purchased_adjusted_qty' => 'decimal:4',
        'year_ago_sold_qty' => 'decimal:4',
        'selling_price' => 'decimal:4',
        'has_previous_purchase' => 'boolean',
    ];

    /**
     * Get the purchase requisition that owns this product.
     */
    public function prRequest()
    {
        return $this->belongsTo(PrRequest::class, 'pr_request_id');
    }

    /**
     * Get the product.
     */
    public function product()
    {
        return $this->belongsTo(\App\Product::class);
    }

    /**
     * Get the variation.
     */
    public function variation()
    {
        return $this->belongsTo(\App\Variation::class);
    }

    /**
     * Get the supplier products for this requisition product.
     */
    public function supplierProducts()
    {
        return $this->hasMany(PrSupplierProduct::class, 'pr_product_id');
    }

    /**
     * Get purchase lines linked to this requisition product.
     */
    public function purchaseLines()
    {
        return $this->hasMany(\App\PurchaseLine::class, 'purchase_requisition_line_id');
    }

    /**
     * Scope to filter by business.
     */
    public function scopeForBusiness($query, $businessId)
    {
        return $query->where('business_id', $businessId);
    }
}
