<?php

namespace App\Modules\Procurement\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Procurement\Services\ProcurementAnalysisService;
use App\Modules\Procurement\Models\Vendor;
use App\Modules\Inventory\Contracts\InventoryServiceInterface;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ProcurementAnalysisController extends Controller
{
    public function __construct(
        protected ProcurementAnalysisService $analysisService,
        protected InventoryServiceInterface $inventoryService,
    ) {}

    public function index(Request $request)
    {
        $filters = $request->only([
            'date_from', 'date_to', 'vendor_id', 'warehouse_id',
        ]);

        // 取得各面向數據
        $kpis = $this->analysisService->getKPIs($filters);
        $deliveryAnalysis = $this->analysisService->getDeliveryAnalysis($filters);
        $quantityAnalysis = $this->analysisService->getQuantityAnalysis($filters);
        $priceTrendAnalysis = $this->analysisService->getPriceTrendAnalysis($filters);

        // 取得篩選器選項（跨模組透過 Service 取得倉庫）
        $warehouses = $this->inventoryService->getAllWarehouses();
        $vendors = Vendor::select('id', 'name', 'code')->orderBy('name')->get();

        return Inertia::render('Procurement/Analysis/Index', [
            'kpis' => $kpis,
            'deliveryAnalysis' => $deliveryAnalysis,
            'quantityAnalysis' => $quantityAnalysis,
            'priceTrendAnalysis' => $priceTrendAnalysis,
            'vendors' => $vendors,
            'warehouses' => $warehouses,
            'filters' => $filters,
        ]);
    }
}
