<?php

namespace App\Modules\Inventory\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Inventory\Models\Category;
use App\Modules\Inventory\Models\Warehouse;
use App\Modules\Inventory\Services\TurnoverService;
use Illuminate\Http\Request;
use Inertia\Inertia;

class InventoryAnalysisController extends Controller
{
    protected $turnoverService;

    public function __construct(TurnoverService $turnoverService)
    {
        $this->turnoverService = $turnoverService;
    }

    public function index(Request $request)
    {
        $filters = $request->only([
            'warehouse_id', 'category_id', 'search', 'per_page', 'sort_by', 'sort_order', 'status'
        ]);

        $defaultPerPage = \App\Modules\Core\Models\SystemSetting::getVal('display.per_page', 10);
        $perPage = (int) $request->input('per_page', $defaultPerPage);
        if (!in_array($perPage, [10, 20, 50, 100])) {
            $perPage = $defaultPerPage;
        }
        $analysisData = $this->turnoverService->getAnalysisData($filters, $perPage);
        $kpis = $this->turnoverService->getKPIs($filters);

        return Inertia::render('Inventory/Analysis/Index', [
            'analysisData' => $analysisData,
            'kpis' => $kpis,
            'warehouses' => Warehouse::select('id', 'name')->get(),
            'categories' => Category::select('id', 'name')->get(),
            'filters' => $filters,
        ]);
    }
}
