<?php

namespace App\Repositories;

use App\Models\StockItem;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;

class StockItemRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new StockItem();
    }

    /**
     * Get items with category
     */
    public function getWithCategory(): Collection
    {
        return $this->with(['category'])
            ->orderBy('item_name', 'asc')
            ->all();
    }

    /**
     * Get items by category
     */
    public function getByCategory(int $categoryId): Collection
    {
        return $this->where('category_id', $categoryId)
            ->orderBy('item_name', 'asc')
            ->all();
    }

    /**
     * Get active items
     */
    public function getActive(): Collection
    {
        return $this->where('status', StockItem::STATUS_ACTIVE)
            ->orderBy('item_name', 'asc')
            ->all();
    }

    /**
     * Search items by name or code
     */
    public function search(string $term): Collection
    {
        $query = $this->getQuery();
        $query->where(function ($q) use ($term) {
            $q->where('item_name', 'like', "%{$term}%")
                ->orWhere('item_code', 'like', "%{$term}%");
        });
        $result = $query->get();
        $this->resetQuery();
        return $result;
    }

    /**
     * Get low stock items
     */
    public function getLowStock(): Collection
    {
        $query = $this->getQuery();
        $query->whereColumn('quantity', '<=', 'min_stock')
            ->where('status', StockItem::STATUS_ACTIVE)
            ->orderBy('quantity', 'asc');
        $result = $query->get();
        $this->resetQuery();
        return $result;
    }

    /**
     * Get item by code
     */
    public function findByCode(string $code): ?StockItem
    {
        $query = $this->getQuery();
        $result = $query->where('item_code', $code)->first();
        $this->resetQuery();
        return $result;
    }

    /**
     * Get items for dropdown
     */
    public function getForDropdown(): Collection
    {
        return $this->where('status', StockItem::STATUS_ACTIVE)
            ->orderBy('item_name', 'asc')
            ->all(['id', 'item_code', 'item_name', 'category_id']);
    }
}
