<?php

namespace App\Modules\Inventory\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Inventory\Contracts\InventoryServiceInterface;
use App\Modules\Inventory\Models\Category;
use App\Modules\Inventory\Models\Warehouse;
use Illuminate\Http\Request;
use Inertia\Inertia;

class StockQueryController extends Controller
{
    protected InventoryServiceInterface $inventoryService;

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

    /**
     * 即時庫存查詢頁面
     */
    public function index(Request $request)
    {
        $filters = $request->only(['warehouse_id', 'category_id', 'search', 'status', 'sort_by', 'sort_order', 'per_page']);
        $perPage = (int) ($filters['per_page'] ?? 10);

        $result = $this->inventoryService->getStockQueryData($filters, $perPage);

        return Inertia::render('Inventory/StockQuery/Index', [
            'filters' => $filters,
            'summary' => $result['summary'],
            'inventories' => [
                'data' => $result['data'],
                'total' => $result['pagination']['total'],
                'per_page' => $result['pagination']['per_page'],
                'current_page' => $result['pagination']['current_page'],
                'last_page' => $result['pagination']['last_page'],
                'links' => $result['pagination']['links'],
            ],
            'warehouses' => Warehouse::select('id', 'name')->orderBy('name')->get(),
            'categories' => Category::select('id', 'name')->orderBy('name')->get(),
        ]);
    }

    /**
     * Excel 匯出
     */
    public function export(Request $request)
    {
        $filters = $request->only(['warehouse_id', 'category_id', 'search', 'status']);

        return \Maatwebsite\Excel\Facades\Excel::download(
            new \App\Modules\Inventory\Exports\StockQueryExport($filters),
            '即時庫存查詢_' . now()->format('Ymd_His') . '.xlsx'
        );
    }
}
