<?php

namespace App\Livewire\Admin\Users;

use App\Models\User;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public string $search = '';
    public string $tab = 'all';

    protected $queryString = [
        'search' => ['except' => ''],
        'tab'    => ['except' => 'all'],
    ];

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function setTab(string $tab)
    {
        $this->tab = $tab;
        $this->resetPage();
    }

    public function updateStatus(string $userId, string $status)
    {
        $user = User::findOrFail($userId);
        $user->update(['status' => $status]);

        $this->dispatch('notify', type: 'success', message: 'Status aktualisiert.');
    }

    public function render()
    {
        $query = User::withCount(['events', 'agentLogs'])
            ->with('subscription.plan')
            ->when($this->search, fn($q) =>
                $q->where('name', 'like', '%' . $this->search . '%')
                  ->orWhere('email', 'like', '%' . $this->search . '%')
            );

        // Tab-Counts (vor Status-Filter)
        $baseQuery = User::when($this->search, fn($q) =>
            $q->where('name', 'like', '%' . $this->search . '%')
              ->orWhere('email', 'like', '%' . $this->search . '%')
        );

        $counts = [
            'all'       => (clone $baseQuery)->count(),
            'active'    => (clone $baseQuery)->where('status', 'active')->count(),
            'suspended' => (clone $baseQuery)->where('status', 'suspended')->count(),
            'blocked'   => (clone $baseQuery)->where('status', 'blocked')->count(),
            'staff'     => (clone $baseQuery)->whereNotIn('role', ['user'])->count(),
        ];

        // Tab-Filter anwenden
        if ($this->tab === 'staff') {
            $query->whereNotIn('role', ['user']);
        } elseif ($this->tab !== 'all') {
            $query->where('status', $this->tab);
        }

        $users = $query->latest()->paginate(25);

        return view('livewire.admin.users.index', compact('users', 'counts'))
            ->layout('layouts.app');
    }
}
