<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AdminUserController extends Controller
{
    public function index(Request $request)
    {
        $query = User::where('is_admin', false)->withCount('licenses');

        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('first_name', 'like', "%{$search}%")
                  ->orWhere('last_name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%");
            });
        }

        if ($filter = $request->input('filter')) {
            if ($filter === 'with_license') {
                $query->has('licenses');
            } elseif ($filter === 'without_license') {
                $query->doesntHave('licenses');
            }
        }

        $users = $query->latest()->paginate(20)->through(fn ($user) => [
            'id' => $user->id,
            'name' => $user->name,
            'initials' => $user->initials,
            'email' => $user->email,
            'licenses_count' => $user->licenses_count,
            'status' => $user->licenses()->where('status', 'active')->exists() ? 'Active' : ($user->licenses()->where('trial_ends_at', '>', now())->exists() ? 'Trial' : 'Inactive'),
            'created_at' => $user->created_at->format('d M Y'),
        ]);

        return Inertia::render('Admin/Users', [
            'users' => $users,
            'filters' => $request->only(['search', 'filter']),
            'total_users' => User::where('is_admin', false)->count(),
        ]);
    }
}
