<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\BaseController;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdminUserController extends BaseController
{
    public function index(Request $request): JsonResponse
    {
        $query = User::query();

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

        if ($role = $request->get('role')) {
            $query->where('role', $role);
        }

        if ($status = $request->get('status')) {
            $query->where('status', $status);
        }

        $users = $query->with('wallet')->orderBy('created_at', 'desc')->paginate($request->get('per_page', 20));

        return $this->paginatedResponse($users);
    }

    public function show(User $user): JsonResponse
    {
        $user->load(['wallet', 'transactions' => fn ($q) => $q->orderBy('created_at', 'desc')->limit(20)]);

        return $this->successResponse($user);
    }

    public function update(Request $request, User $user): JsonResponse
    {
        $validated = $request->validate([
            'status' => ['sometimes', 'in:active,inactive,suspended'],
            'role' => ['sometimes', 'in:user,admin,support'],
        ]);

        $user->update($validated);

        return $this->successResponse($user->fresh(), 'User updated');
    }

    public function suspend(Request $request, User $user): JsonResponse
    {
        $user->update(['status' => 'suspended']);
        return $this->successResponse($user->fresh(), 'User suspended');
    }

    public function activate(Request $request, User $user): JsonResponse
    {
        $user->update(['status' => 'active']);
        return $this->successResponse($user->fresh(), 'User activated');
    }

    public function stats(Request $request, User $user): JsonResponse
    {
        $stats = [
            'total_transactions' => $user->transactions()->count(),
            'successful_transactions' => $user->transactions()->where('status', 'successful')->count(),
            'total_spent' => $user->transactions()->where('status', 'successful')->sum('total_amount'),
            'wallet_balance' => $user->wallet?->balance ?? 0,
            'total_funded' => $user->payments()->where('status', 'successful')->sum('amount'),
        ];

        return $this->successResponse($stats);
    }
}
