<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Friendship;
use App\Models\Log;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\JsonResponse;

class FriendController extends Controller
{
    /**
     * Get all friends of the authenticated user
     */
    public function index(): JsonResponse
    {
        $friends = Auth::user()->friends()
            ->select('users.id', 'users.firstName', 'users.lastName', 'users.email', 'friendships.created_at')
            ->orderBy('friendships.created_at', 'desc')
            ->get();

        return response()->json($friends);
    }

    /**
     * Remove a friend
     */
    public function destroy(int $id): JsonResponse
    {
        $user = Auth::user();
        
        // Check if the friend exists
        $friend = User::find($id);
        if (!$friend) {
            return response()->json([
                'message' => 'User not found'
            ], 404);
        }
        
        // Check if they are actually friends
        if (!$user->isFriendWith($id)) {
            return response()->json([
                'message' => 'You are not friends with this user'
            ], 404);
        }

        $user->removeFriend($id);

        return response()->json([
            'message' => 'Friend removed successfully'
        ]);
    }

    /**
     * Get friend's logs for map viewing
     */
    public function logs(int $id): JsonResponse
    {
        $user = Auth::user();
        
        // Check if they are friends
        if (!$user->isFriendWith($id)) {
            return response()->json([
                'message' => 'You can only view logs of your friends'
            ], 403);
        }

        $friend = User::find($id);
        if (!$friend) {
            return response()->json([
                'message' => 'Friend not found'
            ], 404);
        }

        // Get friend's logs (similar to shared logs but with friend verification)
        $logs = \DB::table('logs')
            ->where('user_id', $friend->id)
            ->where('done', 1) // Only show completed logs
            ->get();

        return response()->json([
            'friend' => [
                'id' => $friend->id,
                'name' => $friend->firstName . ' ' . $friend->lastName,
                'email' => $friend->email
            ],
            'logs' => $logs
        ]);
    }

    /**
     * Get multiple friends' logs for combined map viewing
     */
    public function multipleLogs(Request $request): JsonResponse
    {
        $user = Auth::user();
        
        $request->validate([
            'friend_ids' => 'required|array',
            'friend_ids.*' => 'integer|exists:users,id'
        ]);
        
        $friendIds = $request->input('friend_ids');
        $friendsData = [];
        
        foreach ($friendIds as $friendId) {
            // Check if they are friends
            if (!$user->isFriendWith($friendId)) {
                continue; // Skip non-friends
            }
            
            $friend = User::find($friendId);
            if (!$friend) {
                continue;
            }
            
            // Get only completed logs for the map
            $logs = Log::where('user_id', $friendId)
                ->where('done', 1)
                ->get();
            
            $friendsData[] = [
                'friend' => [
                    'id' => $friend->id,
                    'name' => $friend->firstName . ' ' . $friend->lastName,
                    'email' => $friend->email,
                ],
                'logs' => $logs
            ];
        }
        
        return response()->json([
            'friends' => $friendsData
        ]);
    }

    /**
     * Get friends statistics
     */
    public function statistics(): JsonResponse
    {
        $user = Auth::user();
        
        $stats = [
            'total_friends' => $user->friends()->count(),
            'pending_invitations' => $user->sentInvitations()->pending()->count(),
            'recent_friends' => $user->friends()
                ->orderBy('friendships.created_at', 'desc')
                ->limit(5)
                ->select('users.firstName', 'users.lastName', 'friendships.created_at')
                ->get()
        ];

        return response()->json($stats);
    }
}
