<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Warehouse;

use Inertia\Inertia;

class WarehouseController extends Controller
{
    public function index(Request $request)
    {
        $query = Warehouse::query();

        if ($request->has('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('code', 'like', "%{$search}%");
            });
        }

        $warehouses = $query->withSum('inventories as total_quantity', 'quantity')
            ->withCount(['inventories as low_stock_count' => function ($query) {
                $query->whereColumn('quantity', '<', 'safety_stock');
            }])
            ->orderBy('created_at', 'desc')
            ->paginate(10)
            ->withQueryString();

        return Inertia::render('Warehouse/Index', [
            'warehouses' => $warehouses,
            'filters' => $request->only(['search']),
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'address' => 'nullable|string|max:255',
            'description' => 'nullable|string',
        ]);

        // Auto-generate code
        $prefix = 'WH';
        $lastWarehouse = Warehouse::latest('id')->first();
        $nextId = $lastWarehouse ? $lastWarehouse->id + 1 : 1;
        $code = $prefix . str_pad($nextId, 3, '0', STR_PAD_LEFT);

        $validated['code'] = $code;

        Warehouse::create($validated);

        return redirect()->back()->with('success', '倉庫已建立');
    }

    public function update(Request $request, Warehouse $warehouse)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'address' => 'nullable|string|max:255',
            'description' => 'nullable|string',
        ]);

        $warehouse->update($validated);

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

    public function destroy(Warehouse $warehouse)
    {
        // 檢查是否有相關聯的採購單
        if ($warehouse->purchaseOrders()->exists()) {
            return redirect()->back()->with('error', '無法刪除：該倉庫有相關聯的採購單，請先處理採購單。');
        }

        \Illuminate\Support\Facades\DB::transaction(function () use ($warehouse) {
            // 刪除庫存異動紀錄 (透過庫存關聯)
            foreach ($warehouse->inventories as $inventory) {
                // 刪除該庫存的所有異動紀錄
                $inventory->transactions()->delete();
            }
            
            // 刪除庫存項目
            $warehouse->inventories()->delete();

            // 刪除倉庫
            $warehouse->delete();
        });

        return redirect()->back()->with('success', '倉庫及其庫存與紀錄已刪除');
    }
}
