@php
    $businessId = auth()->user()->business_id;
    $actions = \Illuminate\Support\Facades\DB::table('delivery_corrective_actions as action')
        ->join('operational_documents as delivery', 'delivery.id', '=', 'action.delivery_id')
        ->leftJoin('projects as project', 'project.id', '=', 'delivery.project_id')
        ->leftJoin('users as assignee', 'assignee.id', '=', 'action.assigned_to')
        ->leftJoin('follow_ups as follow_up', 'follow_up.id', '=', 'action.follow_up_id')
        ->where('action.business_id', $businessId)->where('action.status', '!=', 'completed')
        ->select('action.*', 'delivery.reference_number as delivery_reference', 'delivery.status as delivery_status', 'project.id as project_id', 'project.name as project_name', 'assignee.name as assignee_name', 'follow_up.follow_up_at')
        ->orderByRaw('follow_up.follow_up_at IS NULL, follow_up.follow_up_at')->limit(20)->get();
    $overdue = $actions->filter(fn ($action) => $action->follow_up_at && \Carbon\Carbon::parse($action->follow_up_at)->isPast())->count();
@endphp
<div class="card mt-4"><div class="card-header d-flex justify-content-between"><span>Delivery corrective actions</span><span><span class="badge bg-warning text-dark">Open: {{ $actions->count() }}</span> <span class="badge bg-danger">Overdue: {{ $overdue }}</span></span></div><div class="card-body table-responsive"><table class="table table-sm mb-0"><thead><tr><th>Delivery</th><th>Project</th><th>Assignee</th><th>Due date</th><th>Status</th></tr></thead><tbody>
    @forelse ($actions as $action)
        <tr><td><a href="{{ route('operational-documents.index', ['deliveries', 'record' => $action->delivery_id]) }}">{{ $action->delivery_reference }}</a><small class="d-block {{ $action->delivery_status === 'rejected' ? 'text-danger' : 'text-muted' }}">{{ ucwords(str_replace('_', ' ', $action->delivery_status)) }}</small></td><td>@if($action->project_id)<a href="{{ route('projects-view', ['id' => $action->project_id]) }}">{{ $action->project_name }}</a>@else — @endif</td><td>{{ $action->assignee_name ?? 'Unassigned' }}</td><td class="{{ $action->follow_up_at && \Carbon\Carbon::parse($action->follow_up_at)->isPast() ? 'text-danger fw-bold' : '' }}">{{ $action->follow_up_at ? \Carbon\Carbon::parse($action->follow_up_at)->format('Y-m-d H:i') : 'Not scheduled' }}</td><td>{{ ucwords($action->status) }}</td></tr>
    @empty <tr><td colspan="5" class="text-muted">No open corrective actions.</td></tr>
    @endforelse
</tbody></table></div></div>
