@props(['module', 'record'])
@php
    $businessId = $record->business_id;
    $accountId = $module === 'accounts' ? $record->id : ($record->account_id ?? null);
    $dealId = $module === 'deals' ? $record->id : ($record->deal_id ?? null);
    $projectId = $module === 'projects' ? $record->id : null;
    $caseId = $module === 'cases' ? $record->id : null;
    $projectIds = \App\Models\Project::where('business_id', $businessId)->where(function ($query) use ($accountId, $dealId, $projectId) { if ($projectId) $query->whereKey($projectId); else { if ($accountId) $query->where('account_id', $accountId); if ($dealId) $query->orWhere('deal_id', $dealId); } })->pluck('id');
    $documents = \App\Models\OperationalDocument::where('business_id', $businessId)->where(function ($query) use ($accountId, $dealId, $projectIds) { if ($accountId) $query->orWhere('account_id', $accountId); if ($dealId) $query->orWhere('deal_id', $dealId); if ($projectIds->isNotEmpty()) $query->orWhereIn('project_id', $projectIds); })->get();
    $documentIds = $documents->pluck('id');
    $entries = collect();
    $add = function (string $type, string $title, $date, ?string $status, ?int $ownerId, string $url, string $detail = '') use (&$entries) { if ($date) $entries->push((object) compact('type', 'title', 'date', 'status', 'ownerId', 'url', 'detail')); };
    \App\Models\Activity::where('business_id', $businessId)->where(function ($query) use ($accountId, $dealId, $projectIds, $caseId) { if ($accountId) $query->orWhere('account_id', $accountId); if ($dealId) $query->orWhere('deal_id', $dealId); if ($caseId) $query->orWhere('case_id', $caseId); if ($projectIds->isNotEmpty()) $query->orWhereIn('project_id', $projectIds); })->get()->each(fn ($activity) => $add('Activity', $activity->title ?: $activity->subject ?: 'CRM activity', $activity->completed_at ?: $activity->sent_at ?: $activity->start_date ?: $activity->created_at, $activity->lifecycle_status ?: $activity->email_status ?: $activity->status, $activity->owner_id, route('related-activity.index', [$module, $record->id]), $activity->next_action_type === 'none' ? 'No next action: '.$activity->no_next_action_reason : ($activity->next_action_type ? ucwords(str_replace('_', ' ', $activity->next_action_type)).': '.$activity->next_action : ($activity->outcome ?: $activity->description ?: ''))));
    $documents->each(fn ($document) => $add(ucwords(rtrim(str_replace('-', ' ', $document->type), 's')), $document->reference_number, $document->created_at, $document->status, $document->owner_id, route('operational-documents.index', [$document->type, 'record' => $document->id]), 'Workflow record'));
    $documentIds->isNotEmpty() && \Illuminate\Support\Facades\DB::table('operational_document_histories')->whereIn('operational_document_id', $documentIds)->get()->each(function ($history) use ($documents, $add) { $document = $documents->firstWhere('id', $history->operational_document_id); if ($document) $add('Approval / workflow', $document->reference_number.' — '.ucwords(str_replace('_', ' ', $history->action)), $history->created_at, $history->to_status, $history->user_id, route('operational-documents.index', [$document->type, 'record' => $document->id]), $history->comment ?: ''); });
    if ($accountId) { \Illuminate\Support\Facades\DB::table('payments')->where('business_id', $businessId)->where('account_id', $accountId)->get()->each(fn ($payment) => $add('Payment', $payment->reference, $payment->received_at ?: $payment->created_at, $payment->status, $payment->verified_by, route('payments.index').'#payment-'.$payment->id, $payment->payer.' · '.number_format((float) $payment->amount, 2))); \Illuminate\Support\Facades\DB::table('receipts as receipt')->join('payments as payment', 'payment.id', '=', 'receipt.payment_id')->where('receipt.business_id', $businessId)->where('payment.account_id', $accountId)->select('receipt.*', 'payment.id as payment_id', 'payment.reference as payment_reference', 'payment.verified_by')->get()->each(fn ($receipt) => $add('Receipt', $receipt->receipt_number, $receipt->issued_at ?: $receipt->created_at, 'verified', $receipt->verified_by, route('payments.index').'#payment-'.$receipt->payment_id, 'For payment '.$receipt->payment_reference)); }
    $projectIds->isNotEmpty() && \Illuminate\Support\Facades\DB::table('project_risks_issues')->where('business_id', $businessId)->whereIn('project_id', $projectIds)->get()->each(fn ($item) => $add(ucfirst($item->type), $item->title, $item->created_at, $item->status, $item->owner_id, route('projects-view', ['id' => $item->project_id]), ucfirst($item->severity).' severity · '.$item->mitigation));
    $documentIds->isNotEmpty() && \Illuminate\Support\Facades\DB::table('delivery_corrective_actions as action')->join('operational_documents as delivery', 'delivery.id', '=', 'action.delivery_id')->leftJoin('follow_ups as follow_up', 'follow_up.id', '=', 'action.follow_up_id')->where('action.business_id', $businessId)->whereIn('action.delivery_id', $documentIds)->select('action.*', 'delivery.reference_number', 'follow_up.follow_up_at')->get()->each(fn ($action) => $add('Corrective action', 'Delivery remediation: '.$action->reference_number, $action->completed_at ?: $action->follow_up_at ?: $action->created_at, $action->status, $action->assigned_to, route('operational-documents.index', ['deliveries', 'record' => $action->delivery_id]), $action->reason));
    $userNames = \App\Models\User::where('business_id', $businessId)->pluck('name', 'id');
    $types = $entries->pluck('type')->unique()->sort()->values(); $statuses = $entries->pluck('status')->filter()->unique()->sort()->values();
    $selectedType = request('operational_timeline_type'); $selectedOwner = request('operational_timeline_owner'); $selectedStatus = request('operational_timeline_status'); $from = request('operational_timeline_from'); $to = request('operational_timeline_to');
    $entries = $entries->filter(function ($entry) use ($selectedType, $selectedOwner, $selectedStatus, $from, $to) { $date = \Carbon\Carbon::parse($entry->date); return (! $selectedType || $entry->type === $selectedType) && (! $selectedOwner || (string) $entry->ownerId === (string) $selectedOwner) && (! $selectedStatus || $entry->status === $selectedStatus) && (! $from || $date->gte(\Carbon\Carbon::parse($from)->startOfDay())) && (! $to || $date->lte(\Carbon\Carbon::parse($to)->endOfDay())); })->sortByDesc('date');
@endphp
<div class="card mt-4">
    <div class="card-header"><h5 class="mb-0">End-to-end operational timeline</h5></div>
    <div class="card-body">
        <form method="GET" class="row g-2 mb-3">
            @foreach(request()->except(['operational_timeline_type','operational_timeline_owner','operational_timeline_status','operational_timeline_from','operational_timeline_to','page']) as $key => $value)
                @if(is_scalar($value))
                    <input type="hidden" name="{{ $key }}" value="{{ $value }}">
                @endif
            @endforeach
            <div class="col-md-3"><select name="operational_timeline_type" class="form-select"><option value="">All record types</option>@foreach($types as $type)<option value="{{ $type }}" @selected($selectedType === $type)>{{ $type }}</option>@endforeach</select></div>
            <div class="col-md-2"><select name="operational_timeline_owner" class="form-select"><option value="">All owners</option>@foreach($userNames as $id => $name)<option value="{{ $id }}" @selected((string) $selectedOwner === (string) $id)>{{ $name }}</option>@endforeach</select></div>
            <div class="col-md-2"><select name="operational_timeline_status" class="form-select"><option value="">All statuses</option>@foreach($statuses as $status)<option value="{{ $status }}" @selected($selectedStatus === $status)>{{ ucwords(str_replace('_', ' ', $status)) }}</option>@endforeach</select></div>
            <div class="col-md-2"><input type="date" name="operational_timeline_from" value="{{ $from }}" class="form-control"></div>
            <div class="col-md-2"><input type="date" name="operational_timeline_to" value="{{ $to }}" class="form-control"></div>
            <div class="col-md-1"><button class="btn btn-outline-primary w-100">Apply Filters</button></div>
        </form>
        <div class="list-group list-group-flush">
            @forelse($entries as $entry)
                <a class="list-group-item list-group-item-action" href="{{ $entry->url }}"><div class="d-flex justify-content-between"><strong>{{ $entry->type }} · {{ $entry->title }}</strong><small>{{ \Carbon\Carbon::parse($entry->date)->format('M d, Y H:i') }}</small></div><small class="text-muted">{{ $entry->status ? ucwords(str_replace('_', ' ', $entry->status)).' · ' : '' }}{{ $entry->ownerId ? ($userNames[$entry->ownerId] ?? 'Former user') : 'System' }}</small>@if($entry->detail)<div class="small">{{ \Illuminate\Support\Str::limit($entry->detail, 180) }}</div>@endif</a>
            @empty
                <div class="text-muted p-3">No timeline entries match these filters.</div>
            @endforelse
        </div>
    </div>
</div>
