@props(['document'])
@php
    $documents = \App\Models\OperationalDocument::where('business_id', $document->business_id)->get()->keyBy('id');
    $upstream = collect(); $cursor = $document;
    while ($cursor->parent_id && $documents->has($cursor->parent_id)) { $cursor = $documents[$cursor->parent_id]; $upstream->prepend($cursor); }
    $root = $upstream->first() ?? $document;
    $chain = $upstream->push($document);
    $descendants = collect(); $queue = collect([$document->id]);
    while ($queue->isNotEmpty()) { $parents = $queue; $queue = $documents->filter(fn($item) => in_array($item->parent_id, $parents->all(), true))->pluck('id'); $descendants = $descendants->merge($documents->only($queue)); }
    $chain = $chain->merge($descendants)->unique('id')->values();
    $quote = $root->type === 'sales-orders' && $root->trade_document_id ? \App\Models\TradeDocument::whereKey($root->trade_document_id)->where('business_id', $document->business_id)->first() : null;
    $events = \Illuminate\Support\Facades\DB::table('operational_document_histories as history')->leftJoin('users as user', 'user.id', '=', 'history.user_id')->whereIn('history.operational_document_id', $chain->pluck('id'))->select('history.created_at as happened_at','history.action','history.from_status','history.to_status','history.comment','user.name as user_name','history.operational_document_id')->get()->map(fn($event) => (object) ['at'=>$event->happened_at,'label'=>ucwords(str_replace('_',' ', $event->action)),'detail'=>trim(($event->from_status ? $event->from_status.' → ' : '').($event->to_status ?? '').($event->comment ? ': '.$event->comment : '')),'user'=>$event->user_name]);
    if ($quote) $events = $events->merge($quote->approvalHistories()->get()->map(fn($event) => (object) ['at'=>$event->created_at,'label'=>'Quotation '.ucwords(str_replace('_',' ', $event->action)),'detail'=>trim(($event->from_status ? $event->from_status.' → ' : '').($event->to_status ?? '').($event->comment ? ': '.$event->comment : '')),'user'=>null]));
    $events = $events->sortByDesc('at')->values();
    $nextTypes = ['sales-orders'=>'contracts','contracts'=>'handovers','handovers'=>'deliveries','deliveries'=>'invoices']; $requiredStatuses = ['sales-orders'=>'approved','contracts'=>'active','handovers'=>'approved','deliveries'=>'customer_sign_off'];
    $next = $nextTypes[$document->type] ?? null; $child = $documents->first(fn($item) => $item->parent_id === $document->id && $item->type === $next);
    $required = match ($document->type) {'sales-orders'=>['quotation_number','payment_terms','delivery_terms','products_services','grand_total','expected_delivery_date'],'contracts'=>['contract_name','contract_type','start_date','end_date','contract_value','deliverables','scope_of_work','contract_document'],'handovers'=>['project_name','project_manager_id','reviewer_id','project_team','scope_of_work','requirements','deliverables','handover_checklist'],'deliveries'=>['delivery_name','delivery_manager_id','delivery_type','version_release','environment','handover_document','deliverables','customer_sign_off_reference','completion_owner_id','completion_date'],default=>[]};
    $missing = collect($required)->filter(fn($field) => blank(($document->details ?? [])[$field] ?? $document->{$field}))->map(fn($field) => ucwords(str_replace('_',' ', $field)))->values();
    $blocked = !$next ? null : ($child ? ucfirst(rtrim(str_replace('-', ' ', $next), 's')).' already exists.' : ($document->status !== $requiredStatuses[$document->type] ? 'Requires '.ucwords(str_replace('_',' ', $requiredStatuses[$document->type])).' status.' : ($missing->isNotEmpty() ? 'Missing: '.$missing->implode(', ').'.' : null)));
@endphp
<details class="mt-2" open><summary class="small text-primary">Commercial workflow trace</summary><div class="border rounded p-2 mt-1 small"><div class="mb-2"><strong>Chain:</strong> @if($quote)<a href="{{ route('workflow.index', ['module'=>'trade-documents']) }}">Quotation {{ $quote->document_number }}</a> → @endif @foreach($chain as $node)<a href="{{ route('operational-documents.index', ['type'=>$node->type, 'record'=>$node->id]) }}" class="{{ $node->id===$document->id?'fw-bold':'' }}">{{ ucwords(rtrim(str_replace('-', ' ', $node->type), 's')) }} {{ $node->reference_number }}</a>@if(!$loop->last) → @endif @endforeach</div>@if($next)<div class="mb-2"><strong>Next action:</strong> @if($blocked)<span class="text-warning">Blocked — {{ $blocked }}</span>@else<a class="btn btn-sm btn-outline-success" href="{{ route('operational-documents.next.preview', $document) }}">Create {{ ucwords(rtrim(str_replace('-', ' ', $next), 's')) }}</a>@endif</div>@endif<details><summary>Approval, return, resubmission &amp; conversion events ({{ $events->count() }})</summary><div class="mt-1">@forelse($events as $event)<div>{{ \Carbon\Carbon::parse($event->at)->format('Y-m-d H:i') }} · <strong>{{ $event->label }}</strong>@if($event->detail) — {{ $event->detail }}@endif @if($event->user)<span class="text-muted">by {{ $event->user }}</span>@endif</div>@empty<div class="text-muted">No workflow events recorded yet.</div>@endforelse</div></details></div></details>
