<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $query = \App\Models\User::withCount('orders')->latest();
        if ($request->search) {
            $query->where('name','like',"%{$request->search}%")
                  ->orWhere('email','like',"%{$request->search}%");
        }
        $users = $query->paginate(20)->withQueryString();
        return view('admin.users.index', compact('users'));
    }

    public function toggleAdmin(\App\Models\User $user)
    {
        if ($user->id === auth()->id()) return back()->with('error', 'Cannot change your own admin status.');
        $user->update(['is_admin' => !$user->is_admin]);
        return back()->with('success', "User {$user->name} admin status updated.");
    }
}
