<?php

namespace App\Models;

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

class InventoryLot extends Model
{
    protected $fillable = [
        'product_id',
        'branch_id',
        'location_id',
        'batch_no',
        'expiry_date',
        'cost_price',
        'quantity_received',
        'quantity_remaining',
        'source_type',
        'source_id',
    ];

    protected $casts = [
        'cost_price' => 'decimal:2',
        'quantity_received' => 'decimal:2',
        'quantity_remaining' => 'decimal:2',
        'expiry_date' => 'date',
    ];

    // ─── Relationships ───────────────────────────

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

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

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

    // ─── Scopes ──────────────────────────────────

    /**
     * Only lots that still have remaining quantity
     */
    public function scopeAvailable($query)
    {
        return $query->where('quantity_remaining', '>', 0);
    }

    /**
     * FIFO order — oldest first
     */
    public function scopeFifoOrder($query)
    {
        return $query->orderBy('created_at', 'asc')->orderBy('id', 'asc');
    }

    /**
     * Filter by product, branch, and optionally location
     */
    public function scopeForStock($query, int $productId, int $branchId, ?int $locationId = null)
    {
        $query->where('product_id', $productId)
              ->where('branch_id', $branchId);

        if ($locationId !== null) {
            $query->where('location_id', $locationId);
        }

        return $query;
    }

    /**
     * Filter for lots expiring before a given date
     */
    public function scopeExpiringBefore($query, $date)
    {
        return $query->whereNotNull('expiry_date')->where('expiry_date', '<=', $date);
    }
}
