<?php
namespace App\Http\Controllers\Admin\Inventory;
use App\Http\Controllers\Controller;
use App\Models\Inventory\Inventory;
use App\Models\Inventory\Material;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class StockController extends Controller
{
    /**
     * 库存台账 — 汇总 inventories 表，关联 material 信息
     * GET /inventory/stock
     */
    public function index(Request $request): JsonResponse
    {
        $query = Inventory::query()
            ->with(['warehouse', 'material'])
            ->when($request->warehouse_id, fn($q, $v) => $q->where('warehouse_id', $v))
            ->when($request->material_id, fn($q, $v) => $q->where('material_id', $v))
            ->when($request->low_stock, fn($q) => $q->whereRaw('quantity <= (SELECT min_stock FROM materials WHERE materials.id = inventories.material_id AND min_stock IS NOT NULL)'));

        return $this->paginate($query->paginate($request->input('per_page', 20)));
    }

    /**
     * 导出库存台账
     * GET /inventory/stock/export
     */
    public function export(Request $request): JsonResponse
    {
        $rows = Inventory::with(['warehouse', 'material'])
            ->when($request->warehouse_id, fn($q, $v) => $q->where('warehouse_id', $v))
            ->get()
            ->map(fn($inv) => [
                'warehouse'     => $inv->warehouse?->name,
                'material_code' => $inv->material?->code,
                'material_name' => $inv->material?->name,
                'unit'          => $inv->material?->unit,
                'quantity'      => $inv->quantity,
                'batch_no'      => $inv->batch_no,
                'expire_date'   => $inv->expire_date?->toDateString(),
                'safety_stock'  => $inv->material?->min_stock,
                'updated_at'    => $inv->updated_at?->toDateTimeString(),
            ]);

        return $this->success(['rows' => $rows, 'total' => $rows->count()]);
    }
}
