<?php

namespace App\Modules\Inventory\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Inventory\Models\StoreRequisition;
use App\Modules\Inventory\Models\Warehouse;
use App\Modules\Inventory\Models\Product;
use App\Modules\Inventory\Models\Inventory;
use App\Modules\Inventory\Services\StoreRequisitionService;
use App\Modules\Core\Contracts\CoreServiceInterface;
use Illuminate\Http\Request;
use Inertia\Inertia;

class StoreRequisitionController extends Controller
{
    protected StoreRequisitionService $service;
    protected CoreServiceInterface $coreService;

    public function __construct(
        StoreRequisitionService $service,
        CoreServiceInterface $coreService
    ) {
        $this->service = $service;
        $this->coreService = $coreService;
    }

    /**
     * 叫貨單列表
     */
    public function index(Request $request)
    {
        $query = StoreRequisition::query();

        // 搜尋（單號）
        if ($request->search) {
            $query->where('doc_no', 'like', "%{$request->search}%");
        }

        // 狀態篩選
        if ($request->status && $request->status !== 'all') {
            $query->where('status', $request->status);
        }

        // 倉庫篩選
        if ($request->warehouse_id) {
            $query->where('store_warehouse_id', $request->warehouse_id);
        }

        // 日期範圍
        if ($request->date_start) {
            $query->whereDate('created_at', '>=', $request->date_start);
        }
        if ($request->date_end) {
            $query->whereDate('created_at', '<=', $request->date_end);
        }

        // 排序
        $sortField = $request->input('sort_by', 'id');
        $sortOrder = $request->input('sort_order', 'desc');
        $allowedSorts = ['id', 'doc_no', 'status', 'created_at', 'submitted_at'];
        if (in_array($sortField, $allowedSorts)) {
            $query->orderBy($sortField, $sortOrder);
        } else {
            $query->orderBy('id', 'desc');
        }

        $perPage = $request->input('per_page', 10);
        $requisitions = $query->paginate($perPage)->withQueryString();

        // 水和倉庫名稱與使用者名稱
        $warehouses = Warehouse::select('id', 'name', 'type')->get();
        $warehouseMap = $warehouses->keyBy('id');

        $userIds = $requisitions->getCollection()
            ->pluck('created_by')
            ->merge($requisitions->getCollection()->pluck('approved_by'))
            ->filter()
            ->unique()
            ->toArray();
        $users = $this->coreService->getUsersByIds($userIds)->keyBy('id');

        $requisitions->getCollection()->transform(function ($req) use ($warehouseMap, $users) {
            $req->store_warehouse_name = $warehouseMap->get($req->store_warehouse_id)?->name ?? '-';
            $req->supply_warehouse_name = $warehouseMap->get($req->supply_warehouse_id)?->name ?? '-';
            $req->creator_name = $users->get($req->created_by)?->name ?? '-';
            $req->approver_name = $users->get($req->approved_by)?->name ?? '-';
            return $req;
        });

        return Inertia::render('StoreRequisition/Index', [
            'requisitions' => $requisitions,
            'filters' => $request->only(['search', 'status', 'warehouse_id', 'date_start', 'date_end', 'sort_by', 'sort_order', 'per_page']),
            'warehouses' => $warehouses->map(fn($w) => ['id' => $w->id, 'name' => $w->name]),
        ]);
    }

    /**
     * 新增頁面
     */
    public function create()
    {
        $warehouses = Warehouse::select('id', 'name', 'type')->get();
        $products = Product::select('id', 'name', 'code', 'base_unit_id')
            ->with('baseUnit:id,name')
            ->where('is_active', true)
            ->get();

        return Inertia::render('StoreRequisition/Create', [
            'warehouses' => $warehouses->map(fn($w) => [
                'id' => $w->id,
                'name' => $w->name,
                'type' => $w->type?->value,
            ]),
            'products' => $products->map(fn($p) => [
                'id' => $p->id,
                'name' => $p->name,
                'code' => $p->code,
                'unit_name' => $p->baseUnit?->name,
            ]),
        ]);
    }

    /**
     * 儲存叫貨單
     */
    public function store(Request $request)
    {
        $request->validate([
            'store_warehouse_id' => 'required|exists:warehouses,id',
            'remark' => 'nullable|string|max:500',
            'items' => 'required|array|min:1',
            'items.*.product_id' => 'required|exists:products,id',
            'items.*.requested_qty' => 'required|numeric|min:0.01',
            'items.*.remark' => 'nullable|string|max:200',
        ], [
            'items.required' => '至少需要一項商品',
            'items.min' => '至少需要一項商品',
            'items.*.requested_qty.min' => '需求數量必須大於 0',
        ]);

        $requisition = $this->service->create(
            $request->only(['store_warehouse_id', 'remark']),
            $request->items,
            auth()->id()
        );

        // 如果需要直接提交
        if ($request->boolean('submit_immediately')) {
            $this->service->submit($requisition, auth()->id());
            return redirect()->route('store-requisitions.index')
                ->with('success', '叫貨單已提交審核');
        }

        return redirect()->route('store-requisitions.show', $requisition->id)
            ->with('success', '叫貨單已儲存為草稿');
    }

    /**
     * 叫貨單詳情
     */
    public function show($id)
    {
        $requisition = StoreRequisition::with(['items.product.baseUnit'])->findOrFail($id);

        // 水和倉庫
        $warehouses = Warehouse::select('id', 'name', 'type')->get();
        $warehouseMap = $warehouses->keyBy('id');

        $requisition->store_warehouse_name = $warehouseMap->get($requisition->store_warehouse_id)?->name ?? '-';
        $requisition->supply_warehouse_name = $warehouseMap->get($requisition->supply_warehouse_id)?->name ?? '-';

        // 水和使用者
        $userIds = collect([$requisition->created_by, $requisition->approved_by])->filter()->unique()->toArray();
        $users = $this->coreService->getUsersByIds($userIds)->keyBy('id');
        $requisition->creator_name = $users->get($requisition->created_by)?->name ?? '-';
        $requisition->approver_name = $users->get($requisition->approved_by)?->name ?? '-';

        // 水和明細商品資訊
        $requisition->items->transform(function ($item) {
            $item->product_name = $item->product?->name ?? '-';
            $item->product_code = $item->product?->code ?? '-';
            $item->unit_name = $item->product?->baseUnit?->name ?? '-';
            return $item;
        });

        // 取得庫存資訊（顯示該商品在申請倉庫的現有庫存量）
        $productIds = $requisition->items->pluck('product_id')->toArray();
        $inventories = Inventory::where('warehouse_id', $requisition->store_warehouse_id)
            ->whereIn('product_id', $productIds)
            ->select('product_id')
            ->selectRaw('SUM(quantity) as total_qty')
            ->groupBy('product_id')
            ->get()
            ->keyBy('product_id');

        $requisition->items->transform(function ($item) use ($inventories) {
            $item->current_stock = $inventories->get($item->product_id)?->total_qty ?? 0;
            return $item;
        });

        // 操作紀錄
        $activities = \Spatie\Activitylog\Models\Activity::where('subject_type', StoreRequisition::class)
            ->where('subject_id', $requisition->id)
            ->orderBy('created_at', 'desc')
            ->get();

        return Inertia::render('StoreRequisition/Show', [
            'requisition' => $requisition,
            'warehouses' => $warehouses->map(fn($w) => ['id' => $w->id, 'name' => $w->name]),
            'activities' => $activities,
        ]);
    }

    /**
     * 編輯頁面
     */
    public function edit($id)
    {
        $requisition = StoreRequisition::with(['items.product.baseUnit'])->findOrFail($id);

        if (!in_array($requisition->status, ['draft', 'rejected'])) {
            return redirect()->route('store-requisitions.show', $id)
                ->with('error', '僅能編輯草稿或被駁回的叫貨單');
        }

        $warehouses = Warehouse::select('id', 'name', 'type')->get();
        $products = Product::select('id', 'name', 'code', 'base_unit_id')
            ->with('baseUnit:id,name')
            ->where('is_active', true)
            ->get();

        return Inertia::render('StoreRequisition/Create', [
            'requisition' => $requisition,
            'warehouses' => $warehouses->map(fn($w) => [
                'id' => $w->id,
                'name' => $w->name,
                'type' => $w->type?->value,
            ]),
            'products' => $products->map(fn($p) => [
                'id' => $p->id,
                'name' => $p->name,
                'code' => $p->code,
                'unit_name' => $p->baseUnit?->name,
            ]),
        ]);
    }

    /**
     * 更新叫貨單
     */
    public function update(Request $request, $id)
    {
        $requisition = StoreRequisition::findOrFail($id);

        $request->validate([
            'store_warehouse_id' => 'required|exists:warehouses,id',
            'remark' => 'nullable|string|max:500',
            'items' => 'required|array|min:1',
            'items.*.product_id' => 'required|exists:products,id',
            'items.*.requested_qty' => 'required|numeric|min:0.01',
            'items.*.remark' => 'nullable|string|max:200',
        ]);

        $requisition = $this->service->update(
            $requisition,
            $request->only(['store_warehouse_id', 'remark']),
            $request->items
        );

        // 如果需要直接提交
        if ($request->boolean('submit_immediately')) {
            $this->service->submit($requisition, auth()->id());
            return redirect()->route('store-requisitions.index')
                ->with('success', '叫貨單已重新提交審核');
        }

        return redirect()->route('store-requisitions.show', $requisition->id)
            ->with('success', '叫貨單已更新');
    }

    /**
     * 提交審核
     */
    public function submit($id)
    {
        $requisition = StoreRequisition::findOrFail($id);
        $this->service->submit($requisition, auth()->id());

        return redirect()->route('store-requisitions.show', $id)
            ->with('success', '叫貨單已提交審核');
    }

    /**
     * 核准叫貨單
     */
    public function approve(Request $request, $id)
    {
        $requisition = StoreRequisition::findOrFail($id);

        $request->validate([
            'supply_warehouse_id' => 'required|exists:warehouses,id',
            'items' => 'required|array',
            'items.*.id' => 'required|exists:store_requisition_items,id',
            'items.*.approved_qty' => 'required|numeric|min:0',
        ], [
            'supply_warehouse_id.required' => '請選擇供貨倉庫',
        ]);

        $this->service->approve($requisition, $request->only(['supply_warehouse_id', 'items']), auth()->id());

        return redirect()->route('store-requisitions.show', $id)
            ->with('success', '叫貨單已核准，調撥單已自動產生');
    }

    /**
     * 駁回叫貨單
     */
    public function reject(Request $request, $id)
    {
        $requisition = StoreRequisition::findOrFail($id);

        $request->validate([
            'reject_reason' => 'required|string|max:500',
        ], [
            'reject_reason.required' => '請填寫駁回原因',
        ]);

        $this->service->reject($requisition, $request->reject_reason, auth()->id());

        return redirect()->route('store-requisitions.show', $id)
            ->with('success', '叫貨單已駁回');
    }

    /**
     * 刪除叫貨單（僅限草稿）
     */
    public function destroy($id)
    {
        $requisition = StoreRequisition::findOrFail($id);

        if ($requisition->status !== 'draft') {
            return back()->withErrors(['error' => '僅能刪除草稿狀態的叫貨單']);
        }

        $requisition->items()->delete();
        $requisition->delete();

        return redirect()->route('store-requisitions.index')
            ->with('success', '叫貨單已刪除');
    }
}
