@php
    use App\Models\Task\Task;

    $dtColumns = [
        ['key' => 'title', 'label' => 'Görev', 'sortable' => true, 'sort' => 'title'],
        ['key' => 'relations', 'label' => 'İlişkili Kayıtlar'],
        ['key' => 'assignees', 'label' => 'Atananlar'],
        ['key' => 'priority', 'label' => 'Öncelik', 'sortable' => true, 'sort' => 'priority', 'align' => 'center', 'width' => '110px'],
        ['key' => 'due_date', 'label' => 'Son Tarih', 'sortable' => true, 'sort' => 'due_date', 'width' => '150px'],
        ['key' => 'status', 'label' => 'Durum', 'sortable' => true, 'sort' => 'status', 'align' => 'center', 'width' => '130px'],
        ['key' => 'created_at', 'label' => 'Oluşturulma', 'sortable' => true, 'sort' => 'created_at', 'visible' => false, 'width' => '140px'],
        ['key' => '_actions', 'label' => '', 'fixed' => true, 'align' => 'end', 'width' => '90px'],
    ];

    $dtFilters = [
        ['key' => 'status', 'label' => 'Durum', 'value' => request('status'),
         'options' => collect(Task::STATUSES)->map(fn ($m) => $m['label'])->all(), 'placeholder' => 'Tümü'],
        ['key' => 'priority', 'label' => 'Öncelik', 'value' => request('priority'),
         'options' => collect(Task::PRIORITIES)->map(fn ($m) => $m['label'])->all(), 'placeholder' => 'Tümü'],
    ];

    if ($canViewAll) {
        $dtFilters[] = ['key' => 'scope', 'label' => 'Kapsam', 'value' => request('scope'),
            'options' => ['mine' => 'Görevlerim', 'all' => 'Tüm Acente'], 'placeholder' => 'Görevlerim'];
        $dtFilters[] = ['key' => 'assignee', 'label' => 'Atanan', 'value' => request('assignee'),
            'options' => $staffUsers->pluck('full_name', 'id')->all(), 'placeholder' => 'Tümü'];
    }

@endphp

{{-- Görünüm parametresi dt formunun GET gönderimlerinde korunur --}}
<input type="hidden" name="view" value="table" form="dt-form-tasks">
@if(request('filter'))
    <input type="hidden" name="filter" value="{{ request('filter') }}" form="dt-form-tasks">
@endif

<x-data-table
    module="tasks"
    :columns="$dtColumns"
    :filters="$dtFilters"
    :search="request('search', '')"
    search-placeholder="Görev başlığı veya açıklamasında ara…"
    :sort="$sort" :dir="$dir"
    :paginator="$tasks"
    :per-page-options="[10, 25, 50, 100]">

    @forelse($tasks as $task)
        <tr data-quickview-url="{{ route('agency.tasks.quick-view', $task) }}" style="cursor:pointer">
            <td data-col="title">
                <div class="dt-cell-main d-flex align-items-center gap-2">
                    @if($task->is_auto)
                        <i class="fas fa-robot" style="color:#7c3aed; font-size:.75rem;" title="Sistem tarafından oluşturuldu"></i>
                    @endif
                    <span class="{{ $task->status === 'completed' ? 'text-decoration-line-through text-muted' : '' }}">
                        {{ \Illuminate\Support\Str::limit($task->title, 70) }}
                    </span>
                    @if(($task->comments_count ?? 0) > 0)
                        <span class="tk-badge" style="background:#f1f5f9;color:#64748b;" title="{{ $task->comments_count }} not/güncelleme">
                            <i class="far fa-comment"></i> {{ $task->comments_count }}
                        </span>
                    @endif
                </div>
                @if($task->description)
                    <div class="dt-cell-sub">{{ \Illuminate\Support\Str::limit(strip_tags($task->description), 80) }}</div>
                @endif
            </td>
            <td data-col="relations">
                <div class="d-flex flex-wrap gap-1">
                    @foreach($task->relations->take(2) as $rel)
                        <span class="tk-relchip" data-rel-qv="{{ $rel->quickViewUrl() }}" onclick="event.stopPropagation(); if(this.dataset.relQv) openQuickView(this.dataset.relQv);" title="{{ $rel->label() }}">
                            <i class="fas {{ $rel->meta()['icon'] }}"></i>{{ \Illuminate\Support\Str::limit($rel->label(), 24) }}
                        </span>
                    @endforeach
                    @if($task->relations->count() > 2)
                        <span class="tk-relchip">+{{ $task->relations->count() - 2 }}</span>
                    @endif
                </div>
            </td>
            <td data-col="assignees">
                <div class="tk-people">
                    @foreach($task->assignees->take(3) as $user)
                        <span class="tk-person"><span class="tk-avatar">{{ $user->initials }}</span>{{ $user->full_name }}</span>
                    @endforeach
                    @if($task->assignees->count() > 3)
                        <span class="tk-person more" title="{{ $task->assignees->skip(3)->pluck('full_name')->implode(', ') }}">+{{ $task->assignees->count() - 3 }}</span>
                    @endif
                </div>
            </td>
            <td data-col="priority" class="text-center">
                <span class="tk-badge" style="background: {{ $task->priorityMeta()['color'] }}18; color: {{ $task->priorityMeta()['color'] }};">
                    {{ $task->priorityMeta()['label'] }}
                </span>
            </td>
            <td data-col="due_date">
                @if($task->due_date)
                    <span class="tk-due {{ $task->isOverdue() ? 'over' : '' }}">
                        <i class="fas {{ $task->isOverdue() ? 'fa-fire' : 'fa-clock' }}"></i>
                        {{ $task->due_date->translatedFormat('d M Y, H:i') }}
                    </span>
                @else
                    <span class="text-muted">—</span>
                @endif
            </td>
            <td data-col="status" class="text-center">
                <span class="tk-badge" style="background: {{ $task->statusMeta()['color'] }}18; color: {{ $task->statusMeta()['color'] }};">
                    {{ $task->statusMeta()['label'] }}
                </span>
            </td>
            <td data-col="created_at">
                <span class="dt-cell-sub">{{ $task->created_at->translatedFormat('d M Y') }}</span>
            </td>
            <td data-col="_actions" class="text-end">
                <div class="dt-rowact">
                    @if(in_array($task->status, ['pending', 'in_progress'], true))
                        <button type="button" class="dt-iconbtn success" title="Tamamla"
                                onclick="event.stopPropagation(); tkCompleteTask({{ $task->id }}, this)">
                            <i class="fas fa-check"></i>
                        </button>
                    @endif
                    @if($canAssign || $task->created_by === auth()->id())
                        <button type="button" class="dt-iconbtn warn" title="Arşive Al"
                                onclick="event.stopPropagation(); tkArchiveTask({{ $task->id }})">
                            <i class="fas fa-box-archive"></i>
                        </button>
                    @endif
                </div>
            </td>
        </tr>
    @empty
        <tr>
            <td colspan="100">
                <div class="dt-empty">
                    <i class="fas fa-list-check"></i>
                    <h4>Görev bulunamadı</h4>
                    <p>Filtreleri temizleyin veya yeni bir görev oluşturun.</p>
                </div>
            </td>
        </tr>
    @endforelse
</x-data-table>

@push('scripts')
<script>
    function tkCompleteTask(id, btn) {
        btn.disabled = true;
        fetch(`{{ url('agency/tasks') }}/${id}/status`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({ status: 'completed' })
        }).then(r => {
            if (!r.ok) throw new Error();
            location.reload();
        }).catch(() => { btn.disabled = false; appToast('error', 'Görev tamamlanamadı'); });
    }

    function tkArchiveTask(id) {
        appConfirm({
            title: 'Görev arşive alınsın mı?',
            text: 'Arşiv sayfasından dilediğinizde geri alabilirsiniz.',
            icon: 'question',
            confirmButtonText: 'Arşive Al',
        }).then(ok => {
            if (!ok) return;
            fetch(`{{ url('agency/tasks') }}/${id}/archive`, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            }).then(r => {
                if (!r.ok) throw new Error();
                location.reload();
            }).catch(() => appToast('error', 'Görev arşive alınamadı'));
        });
    }
</script>
@endpush
