@props(['delivery'])
@php
    $actions = \Illuminate\Support\Facades\DB::table('delivery_corrective_actions as action')
        ->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', $delivery->business_id)->where('action.delivery_id', $delivery->id)
        ->select('action.*', 'assignee.name as assignee_name', 'follow_up.title as follow_up_title', 'follow_up.follow_up_at', 'follow_up.status as follow_up_status')
        ->latest('action.id')->get();
@endphp
@if ($actions->isNotEmpty())
    <div class="card mt-2 border-warning">
        <div class="card-header d-flex justify-content-between"><span>Delivery corrective actions</span>@if ($delivery->status === 'rejected')<span class="badge bg-warning text-dark">Delivery remains rejected until remediated</span>@endif</div>
        <div class="card-body table-responsive"><table class="table table-sm mb-0"><thead><tr><th>Reason / deliverables</th><th>Assignee</th><th>Due date</th><th>Status</th><th>Linked follow-up</th><th>Completed</th><th></th></tr></thead><tbody>
            @foreach ($actions as $action)
                <tr><td>{{ $action->reason }}<small class="d-block text-muted">{{ $action->affected_deliverables }}</small></td><td>{{ $action->assignee_name ?? 'Unassigned' }}</td><td>{{ $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><td>@if ($action->follow_up_id)<a href="{{ route('workflow.index', 'follow-ups') }}">{{ $action->follow_up_title ?: 'Follow-up #'.$action->follow_up_id }}</a><small class="d-block text-muted">{{ ucwords(str_replace('_', ' ', $action->follow_up_status ?? 'pending')) }}</small>@else <span class="text-muted">None</span>@endif</td><td>{{ $action->completed_at ? \Carbon\Carbon::parse($action->completed_at)->format('Y-m-d H:i') : '—' }}</td><td>@if ($action->status !== 'completed' && ((int) $action->assigned_to === (int) auth()->id() || auth()->user()->is_admin))<form method="POST" action="{{ route('delivery-corrective-actions.complete', $action->id) }}">@csrf<button class="btn btn-sm btn-outline-success">Complete</button></form>@endif</td></tr>
            @endforeach
        </tbody></table></div>
    </div>
@endif
