<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $currentUser = $request->user();
        
        $users = User::select('id', 'name', 'email', 'created_at')
                    ->where('id', '!=', $currentUser->id)
                    ->withCount(['sentFriendRequests as has_sent_request' => function($query) use ($currentUser) {
                        $query->where('sender_id', $currentUser->id)
                              ->where('status', 'pending');
                    }])
                    ->withCount(['receivedFriendRequests as has_received_request' => function($query) use ($currentUser) {
                        $query->where('sender_id', $currentUser->id)
                              ->where('status', 'pending');
                    }])
                    ->withCount(['sentFriendRequests as is_friend' => function($query) use ($currentUser) {
                        $query->where(function($q) use ($currentUser) {
                            $q->where('sender_id', $currentUser->id)
                              ->orWhere('receiver_id', $currentUser->id);
                        })->where('status', 'accepted');
                    }])
                    ->orderBy('created_at', 'desc')
                    ->get()
                    ->map(function($user) {
                        return [
                            'id' => $user->id,
                            'name' => $user->name,
                            'email' => $user->email,
                            'created_at' => $user->created_at,
                            'friend_status' => $user->is_friend ? 'friend' : 
                                             ($user->has_sent_request ? 'request_sent' : 
                                             ($user->has_received_request ? 'request_received' : 'none'))
                        ];
                    });

        return response()->json([
            'success' => true,
            'data' => [
                'users' => $users
            ]
        ]);
    }

    public function show($id)
    {
        $user = User::select('id', 'name', 'email', 'created_at')
                    ->find($id);

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'user' => $user
            ]
        ]);
    }
}