<?php

namespace App\Http\Controllers;

use App\Models\PurchaseProduct;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class RawMaterialStockController extends Controller
{
    private const PER_PAGE_OPTIONS = [5, 10, 25, 50];

    public function index(Request $request): Response
    {
        $perPage = $request->integer('per_page', 10);
        if (! in_array($perPage, self::PER_PAGE_OPTIONS, true)) {
            $perPage = 10;
        }

        $search = $request->string('search')->trim()->toString();

        $stocks = PurchaseProduct::query()
            ->with(['unit:id,name', 'baseUnit:id,name'])
            ->when($search !== '', function ($query) use ($search): void {
                $query->where(function ($q) use ($search): void {
                    $q->where('name', 'like', '%'.$search.'%')
                        ->orWhereHas('unit', function ($unitQuery) use ($search): void {
                            $unitQuery->where('name', 'like', '%'.$search.'%');
                        });
                });
            })
            ->orderByDesc('id')
            ->paginate($perPage)
            ->withQueryString()
            ->through(fn (PurchaseProduct $product): array => [
                'id' => $product->id,
                'name' => $product->name,
                'unit_name' => $product->unit?->name,
                'base_unit_name' => $product->baseUnit?->name,
                'uses_base_unit' => $product->usesBaseUnit(),
                'is_active' => $product->is_active,
                'stock_on_hand' => $product->displayStockOnHand(),
                'stock_in_base' => (string) $product->stock_on_hand,
            ]);

        return Inertia::render('purchases/stocks/index', [
            'stocks' => $stocks,
            'filters' => [
                'search' => $search,
                'per_page' => $perPage,
            ],
        ]);
    }
}
