<?php

namespace App\Http\Controllers;

use App\Models\Warehouse;
use App\Models\Inventory;
use App\Models\Product;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\DB;

class SafetyStockController extends Controller
{
    /**
     * 顯示安全庫存設定頁面
     */
    public function index(Warehouse $warehouse)
    {
        $warehouse->load(['inventories.product.category']);
        
        $allProducts = Product::with(['category', 'baseUnit'])->get();

        // 準備可選商品列表
        $availableProducts = $allProducts->map(function ($product) {
            return [
                'id' => (string) $product->id,
                'name' => $product->name,
                'type' => $product->category ? $product->category->name : '其他',
                'unit' => $product->baseUnit?->name ?? '個',
            ];
        });

        // 準備現有庫存列表 (用於狀態計算)
        $inventories = $warehouse->inventories->map(function ($inv) {
            return [
                'id' => (string) $inv->id,
                'productId' => (string) $inv->product_id,
                'quantity' => (float) $inv->quantity,
                'safetyStock' => (float) $inv->safety_stock,
            ];
        });

        // 準備安全庫存設定列表
        $safetyStockSettings = $warehouse->inventories->filter(function($inv) {
            return !is_null($inv->safety_stock);
        })->map(function ($inv) {
            return [
                'id' => (string) $inv->id,
                'warehouseId' => (string) $inv->warehouse_id,
                'productId' => (string) $inv->product_id,
                'productName' => $inv->product->name,
                'productType' => $inv->product->category ? $inv->product->category->name : '其他',
                'safetyStock' => (float) $inv->safety_stock,
                'unit' => $inv->product->baseUnit?->name ?? '個',
                'updatedAt' => $inv->updated_at->toIso8601String(),
            ];
        })->values();


        return Inertia::render('Warehouse/SafetyStockSettings', [
            'warehouse' => $warehouse,
            'safetyStockSettings' => $safetyStockSettings,
            'inventories' => $inventories,
            'availableProducts' => $availableProducts,
        ]);
    }

    /**
     * 批量儲存安全庫存設定
     */
    public function store(Request $request, Warehouse $warehouse)
    {
        $validated = $request->validate([
            'settings' => 'required|array|min:1',
            'settings.*.productId' => 'required|exists:products,id',
            'settings.*.quantity' => 'required|numeric|min:0',
        ]);

        DB::transaction(function () use ($validated, $warehouse) {
            foreach ($validated['settings'] as $item) {
                Inventory::updateOrCreate(
                    [
                        'warehouse_id' => $warehouse->id,
                        'product_id' => $item['productId'],
                    ],
                    [
                        'safety_stock' => $item['quantity'],
                    ]
                );
            }
        });

        return redirect()->back()->with('success', '安全庫存設定已更新');
    }

    /**
     * 更新單筆安全庫存設定
     */
    public function update(Request $request, Warehouse $warehouse, Inventory $inventory)
    {
        $validated = $request->validate([
            'safetyStock' => 'required|numeric|min:0',
        ]);

        $inventory->update([
            'safety_stock' => $validated['safetyStock'],
        ]);

        return redirect()->back()->with('success', '安全庫存已更新');
    }

    /**
     * 刪除 (歸零) 安全庫存設定
     */
    public function destroy(Warehouse $warehouse, Inventory $inventory)
    {
        $inventory->update([
            'safety_stock' => null,
        ]);

        return redirect()->back()->with('success', '安全庫存設定已移除');
    }
}
