@props(['dsars', 'selectable' => false])

@if($dsars->count())
<table class="table table-hover align-middle border">
    <thead class="table-light">
    <tr>
        @if($selectable)
            <th style="width:36px;">
                {{-- select-all handled by parent --}}
            </th>
        @endif
        <th style="width: 40%">Care Setting / Facility</th>
        <th>DSAR Type</th>
        <th>Sent Date</th>
        <th class="text-center">Status</th>
        <th></th>
    </tr>
    </thead>
    <tbody>
    @foreach($dsars as $dsar)
        @php
            $status = $dsar->status ?? 'pending';
            $badgeClass = match (strtolower($status)) {
                'completed', 'sent' => 'bg-success',
                'approved'          => 'bg-primary',
                'needs posting'     => 'bg-warning text-dark',
                'draft'             => 'bg-secondary',
                'failed'            => 'bg-danger',
                default             => 'bg-info text-dark',
            };
            $isPostable = $selectable && $status === 'needs posting';
        @endphp
        <tr class="{{ $isPostable ? '' : '' }}" wire:key="dsar-row-{{ $dsar->id }}">
            @if($selectable)
                <td>
                    @if($isPostable)
                        <input type="checkbox"
                               class="form-check-input"
                               value="{{ $dsar->id }}"
                               wire:model.live="postIds">
                    @endif
                </td>
            @endif
            <td>
                <div class="fw-bold">{{ $dsar->institution->display_name ?? 'Unknown' }}</div>
                <span class="badge bg-warning border text-dark fw-normal">{{ $dsar->institution->type->display_name ?? 'N/A' }}</span>
            </td>
            <td><span class="badge border text-dark fw-normal">{{ $dsar->institution->dsarType->display_name ?? 'N/A' }}</span></td>
            <td>
                {{ $dsar->created_at->format('d M Y') }}
                @if($dsar->posted_at)
                    <br><small class="text-muted">Posted {{ $dsar->posted_at->format('d M Y') }}</small>
                @endif
            </td>
            <td class="text-center">
                <span class="badge {{ $badgeClass }} w-75">
                    {{ ucwords($status) }}
                </span>
            </td>
            <td>
                <a href="{{ route('dsars.view', $dsar) }}" class="btn btn-md">
                    <span class="mdi mdi-search-web text-primary"></span>
                </a>
            </td>
        </tr>
    @endforeach
    </tbody>
</table>
@else
    <div class="text-center p-5 text-muted">
        <i class="mdi mdi-file-account" style="font-size: 48px;"></i>
        <p class="mt-3 fw-bold">No DSARs have been recorded.</p>
    </div>
@endif
