@props(['module', 'record'])
@php
    $fileQuery = \App\Models\CrmFile::with('uploader')
        ->where('fileable_type', $record::class)->where('fileable_id', $record->id);
    $currentUser = auth()->user();
    $ownerId = $record->owner_id ?? $record->contact_owner_id ?? $record->created_by ?? null;
    if (!$currentUser->hasRole('admin') && !$currentUser->can('manage_crm_files') && (int) $ownerId !== (int) $currentUser->id) {
        $fileQuery->visibleTo($currentUser);
    }
    $embeddedFiles = $fileQuery->orderByDesc('is_current')->orderBy('name')->orderByDesc('version')->get();
@endphp
<div class="crm-file-manager">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="fw-bold mb-0">Files</h5>
        <a class="btn btn-sm btn-light" href="{{ route('crm-files.index', [$module, $record->id]) }}">
            Advanced manager and relationships
        </a>
    </div>
    <form method="POST" action="{{ route('crm-files.store', [$module, $record->id]) }}" enctype="multipart/form-data"
        class="row g-2 border rounded p-3 mb-4">
        @csrf
        <div class="col-md-2"><input class="form-control" name="name" placeholder="Display name"></div>
        <div class="col-md-2"><input class="form-control" name="category" placeholder="Category"></div>
        <div class="col-md-2"><input class="form-control" name="description" placeholder="Description"></div>
        <div class="col-md-2"><select class="form-control" name="access_level"><option value="business">Business</option><option value="team">Team</option><option value="private">Private</option></select></div>
        <div class="col-md-3"><input class="form-control" type="file" name="file" required></div>
        <div class="col-md-1"><button class="btn btn-primary w-100">Add</button></div>
    </form>
    <div class="table-responsive"><table class="table align-middle">
        <thead><tr><th>Name</th><th>Category</th><th>Access</th><th>Version</th><th>Uploaded</th><th></th></tr></thead>
        <tbody>
        @forelse ($embeddedFiles as $file)
            <tr><td>{{ $file->name }}<div class="small text-muted">{{ $file->original_name }}</div></td>
                <td>{{ $file->category ?: '—' }}</td><td>{{ ucfirst($file->access_level) }}</td>
                <td>v{{ $file->version }} @if($file->is_current)<span class="badge bg-success">Current</span>@endif</td>
                <td>{{ $file->created_at->format('M d, Y H:i') }}<div class="small">{{ $file->uploader?->name }}</div></td>
                <td class="text-end"><a class="btn btn-sm btn-light" target="_blank" href="{{ route('crm-files.view', $file) }}">Open</a>
                    <a class="btn btn-sm btn-light" href="{{ route('crm-files.download', $file) }}">Download</a></td></tr>
        @empty <tr><td colspan="6" class="text-muted">No files uploaded.</td></tr> @endforelse
        </tbody>
    </table></div>
</div>
