<?php

namespace Modules\Vrc\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Vrc\Entities\VrcRepairOrderService;
use Modules\Vrc\Entities\VrcRoStageHistory;
use Modules\Vrc\Entities\VrcWorkCenter;

/**
 * Phase 2 — multi-stage workshop board. Repair-order task lines are routed across
 * work centers (Mechanical → Body/Paint → Electrical → QC …); each move is an
 * audited hand-off (vrc_ro_stage_history). This is the Kanban that turns the flat
 * repair order into a tracked multi-stage workflow.
 */
class WorkflowBoardController extends VrcBaseController
{
    private const STAGES = ['queued', 'in_progress', 'done', 'blocked'];

    public function board()
    {
        $this->guard('vrc.workflow.view');
        $bid = $this->businessId();

        $centers = VrcWorkCenter::where('business_id', $bid)->where('is_active', true)
            ->orderBy('sort_order')->orderBy('name')->get();

        $lines = $this->openLines($bid);
        $grouped = $lines->groupBy(fn ($l) => $l->work_center_id ?: 0);

        return view('vrc::workflow.board', compact('centers', 'grouped'));
    }

    public function data()
    {
        $this->guard('vrc.workflow.view');
        $lines = $this->openLines($this->businessId());
        return response()->json($lines->groupBy(fn ($l) => $l->work_center_id ?: 0));
    }

    public function routeLine(Request $request, $line)
    {
        $this->guard('vrc.workflow.manage');

        $data = $this->validate($request, [
            'work_center_id' => 'nullable|integer',
            'stage_status'   => 'required|in:' . implode(',', self::STAGES),
            'note'           => 'nullable|string|max:255',
        ]);

        try {
            $svc = VrcRepairOrderService::where('business_id', $this->businessId())->findOrFail($line);
            $from = $svc->work_center_id;

            $svc->update([
                'work_center_id'   => $data['work_center_id'] ?: null,
                'stage_status'     => $data['stage_status'],
                'stage_entered_at' => now(),
            ]);

            VrcRoStageHistory::create([
                'business_id'             => $this->businessId(),
                'repair_order_id'         => $svc->repair_order_id,
                'repair_order_service_id' => $svc->id,
                'from_work_center_id'     => $from,
                'to_work_center_id'       => $data['work_center_id'] ?: null,
                'actor_id'                => $this->userId(),
                'note'                    => $data['note'] ?? null,
                'created_at'              => now(),
            ]);

            return $this->ok(__('vrc::lang.updated_success'));
        } catch (\Throwable $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    private function openLines(int $bid)
    {
        return VrcRepairOrderService::where('vrc_repair_order_services.business_id', $bid)
            ->join('vrc_repair_orders as ro', 'ro.id', '=', 'vrc_repair_order_services.repair_order_id')
            ->whereNotIn('ro.status', ['completed', 'cancelled', 'delivered'])
            ->orderBy('vrc_repair_order_services.stage_entered_at')
            ->select([
                'vrc_repair_order_services.*',
                'ro.number as ro_number',
                'ro.status as ro_status',
                'ro.vehicle_id as ro_vehicle_id',
            ])
            ->get();
    }
}
