<?php

namespace App\Http\Controllers\Api\InventoryCollection;

use App\Http\Controllers\Controller;
use App\Http\Resources\InventorySOHResource;
use App\Models\Item;
use App\Services\InventoryService;
use Essa\APIToolKit\Api\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class InventorySOHController extends Controller
{
    use ApiResponse;

    protected InventoryService $inventoryService;

    public function __construct(InventoryService $inventoryService)
    {
        $this->inventoryService = $inventoryService;
    }

    public function index(Request $request)
    {
        $farmId = Auth::user()->farm_id;

        $items = Item::with(['movements' => function ($query) use ($farmId) {
            $query->where('farm_id', $farmId);
        }], "category")
            ->withSum([
                'movements as total_in' => function ($query) use ($farmId) {
                    $query->where('farm_id', $farmId)->where('type', 'IN');
                }
            ], 'quantity')
            ->withSum([
                'movements as total_out' => function ($query) use ($farmId) {
                    $query->where('farm_id', $farmId)->where('type', 'OUT');
                }
            ], 'quantity')
            // ->when($request->search, function ($query, $search) {
            //     $query->where(function ($q) use ($search) {
            //         $q->where('name', 'like', "%{$search}%")
            //             ->orWhere('code', 'like', "%{$search}%");
            //     });
            // })
            // ->when($request->has('low_stock'), function ($query) use ($farmId) {
            //     // Only show items at or below reorder point
            //     $query->whereRaw("
            //         (SELECT COALESCE(SUM(CASE WHEN type = 'IN' THEN quantity ELSE -quantity END), 0)
            //          FROM inventory_movements
            //          WHERE item_id = items.id AND farm_id = ?)
            //         <= reorder_point
            //     ", [$farmId]);
            // })
            // ->orderBy('name')
            ->dynamicPaginate();

        if ($items->isEmpty()) {
            return $this->responseNotFound(
                __("messages.not_found", ["module" => __("models.item_plural")])
            );
        }

        return $this->responseSuccess(
            __("messages.display", ["module" => __("models.item_plural")]),
            InventorySOHResource::collection($items)
        );
    }
}
