<?php

namespace App\Modules\Procurement\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Procurement\Models\Vendor;
use App\Modules\Inventory\Contracts\InventoryServiceInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class VendorProductController extends Controller
{
    public function __construct(
        protected InventoryServiceInterface $inventoryService
    ) {}

    /**
     * 新增供貨商品 (Attach)
     */
    public function store(Request $request, Vendor $vendor)
    {
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'last_price' => 'nullable|numeric|min:0',
        ]);

        // 檢查是否已存在
        if ($vendor->products()->where('product_id', $validated['product_id'])->exists()) {
            return redirect()->back()->with('error', '該商品已在供貨清單中');
        }

        $vendor->products()->attach($validated['product_id'], [
            'last_price' => $validated['last_price'] ?? null
        ]);

        // 記錄操作
        $product = $this->inventoryService->getProduct($validated['product_id']);
        activity()
            ->performedOn($vendor)
            ->withProperties([
                'attributes' => [
                    'product_name' => $product->name,
                    'last_price' => $validated['last_price'] ?? null,
                ],
                'sub_subject' => '供貨商品',
                'snapshot' => [
                    'name' => "{$vendor->name}-{$product->name}", // 顯示例如：台積電-紅糖
                    'vendor_name' => $vendor->name,
                    'product_name' => $product->name,
                ]
            ])
            ->event('created')
            ->log('新增供貨商品');

        return redirect()->back()->with('success', '供貨商品已新增');
    }

    /**
     * 更新供貨商品資訊 (Update Pivot)
     */
    public function update(Request $request, Vendor $vendor, $productId)
    {
        $validated = $request->validate([
            'last_price' => 'nullable|numeric|min:0',
        ]);

        // 獲取舊價格
        $old_price = $vendor->products()->where('product_id', $productId)->first()?->pivot?->last_price;

        $vendor->products()->updateExistingPivot($productId, [
            'last_price' => $validated['last_price'] ?? null
        ]);

        // 記錄操作
        $product = $this->inventoryService->getProduct($productId);
        activity()
            ->performedOn($vendor)
            ->withProperties([
                'old' => [
                    'last_price' => $old_price,
                ],
                'attributes' => [
                    'last_price' => $validated['last_price'] ?? null,
                ],
                'sub_subject' => '供貨商品',
                'snapshot' => [
                    'name' => "{$vendor->name}-{$product->name}",
                    'vendor_name' => $vendor->name,
                    'product_name' => $product->name,
                ]
            ])
            ->event('updated')
            ->log('更新供貨商品價格');

        return redirect()->back()->with('success', '供貨資訊已更新');
    }

    /**
     * 移除供貨商品 (Detach)
     */
    public function destroy(Vendor $vendor, $productId)
    {
        // 記錄操作 (需在 detach 前獲取資訊)
        $product = $this->inventoryService->getProduct($productId);
        $old_price = $vendor->products()->where('product_id', $productId)->first()?->pivot?->last_price;
        
        $vendor->products()->detach($productId);

        if ($product) {
            activity()
                ->performedOn($vendor)
                ->withProperties([
                    'old' => [
                        'product_name' => $product->name,
                        'last_price' => $old_price,
                    ],
                    'sub_subject' => '供貨商品',
                    'snapshot' => [
                        'name' => "{$vendor->name}-{$product->name}",
                        'vendor_name' => $vendor->name,
                        'product_name' => $product->name,
                    ]
                ])
                ->event('deleted')
                ->log('移除供貨商品');
        }

        return redirect()->back()->with('success', '供貨商品已移除');
    }
}
