<?php

namespace App\Models;

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

class Inventory extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'item_id',
        'item_name',
        'category_id',
        'category',
        'item_unit',
        'unit_price',
        'quantity',
        'total_price',
        'invoice_img',
        'comments',
        'created_by',
        'updated_by',
        'deleted_by',
        'batch_id',
        'batch_hash',
        'restaurant_id',
        'branch_id',
        'supplier_id',
        'supplier_bill_id',
        'last_transaction_at',
        'transaction_type',
        'reference_type',
        'reference_id',
    ];

    protected $casts = [
        'quantity' => 'decimal:2',
        'unit_price' => 'decimal:2',
        'total_price' => 'decimal:2',
    ];

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

        static::saving(function ($inventory) {
            $inventory->total_price = round($inventory->unit_price * $inventory->quantity, 2);
        });
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    public function deleter()
    {
        return $this->belongsTo(User::class, 'deleted_by');
    }

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

    public function category()
    {
        return $this->belongsTo(InventoryCategory::class, 'category_id');
    }

    public function stockOuts()
    {
        return $this->hasMany(StockOut::class);
    }

    public function getAvailableQuantityAttribute()
    {
        // Calculate available quantity from inventories table
        return static::getCurrentStockForBranch($this->item_id, $this->branch_id);
    }

    public function restaurant()
    {
        return $this->belongsTo(Restaurant::class, 'restaurant_id');
    }

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

    public function scopeForRestaurant($query, $restaurantId)
    {
        return $query->where('restaurant_id', $restaurantId);
    }

    public function scopeForBranch($query, $branchId)
    {
        return $query->where('branch_id', $branchId);
    }

    public function scopeIn($query)
    {
        return $query->where('transaction_type', 'in');
    }

    public function scopeOut($query)
    {
        return $query->where('transaction_type', 'out');
    }

    public function scopeForTransactionType($query, $type)
    {
        return $query->where('transaction_type', $type);
    }

    // New relationships for supplier and transactions
    public function supplier()
    {
        return $this->belongsTo(Supplier::class, 'supplier_id');
    }

    public function supplierBill()
    {
        return $this->belongsTo(SupplierBill::class, 'supplier_bill_id');
    }

    public function transactions()
    {
        return $this->hasMany(InventoryTransaction::class, 'inventory_id');
    }

    // Calculate current stock from inventories table directly
    public function getCurrentStockAttribute()
    {
        if (!$this->item_id || !$this->branch_id) {
            return 0;
        }

        // Sum all 'in' transactions minus all 'out' transactions for this item and branch
        $inTotal = static::where('item_id', $this->item_id)
            ->where('branch_id', $this->branch_id)
            ->where('transaction_type', 'in')
            ->sum('quantity');

        $outTotal = static::where('item_id', $this->item_id)
            ->where('branch_id', $this->branch_id)
            ->where('transaction_type', 'out')
            ->sum('quantity');

        return max(0, $inTotal - $outTotal);
    }

    // Get current stock for specific branch and item
    public static function getCurrentStockForBranch($itemId, $branchId)
    {
        $inTotal = static::where('item_id', $itemId)
            ->where('branch_id', $branchId)
            ->where('transaction_type', 'in')
            ->sum('quantity');

        $outTotal = static::where('item_id', $itemId)
            ->where('branch_id', $branchId)
            ->where('transaction_type', 'out')
            ->sum('quantity');

        return max(0, $inTotal - $outTotal);
    }
}

