<?php

namespace App\Http\Controllers;

use App\Models\FriendRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class FriendController extends Controller
{
    // Send friend request
    public function sendRequest(Request $request, $receiverId)
    {
        $validator = Validator::make([
            'receiver_id' => $receiverId
        ], [
            'receiver_id' => 'required|exists:users,id'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'User not found',
                'errors' => $validator->errors()
            ], 422);
        }

        $sender = $request->user();
        
        // Check if trying to send request to self
        if ($sender->id == $receiverId) {
            return response()->json([
                'success' => false,
                'message' => 'Cannot send friend request to yourself'
            ], 422);
        }

        // Check if already friends
        if ($sender->isFriendWith($receiverId)) {
            return response()->json([
                'success' => false,
                'message' => 'You are already friends with this user'
            ], 422);
        }

        // Check if request already exists
        $existingRequest = FriendRequest::where(function($query) use ($sender, $receiverId) {
            $query->where('sender_id', $sender->id)
                  ->where('receiver_id', $receiverId);
        })->orWhere(function($query) use ($sender, $receiverId) {
            $query->where('sender_id', $receiverId)
                  ->where('receiver_id', $sender->id);
        })->first();

        if ($existingRequest) {
            $message = $existingRequest->status == 'pending' 
                ? 'Friend request already pending'
                : 'Friend request already exists between you two';

            return response()->json([
                'success' => false,
                'message' => $message
            ], 422);
        }

        // Create new friend request
        $friendRequest = FriendRequest::create([
            'sender_id' => $sender->id,
            'receiver_id' => $receiverId,
            'status' => 'pending'
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Friend request sent successfully',
            'data' => [
                'friend_request' => [
                    'id' => $friendRequest->id,
                    'sender_id' => $friendRequest->sender_id,
                    'receiver_id' => $friendRequest->receiver_id,
                    'status' => $friendRequest->status,
                    'created_at' => $friendRequest->created_at
                ]
            ]
        ], 201);
    }

    // Accept friend request
    public function acceptRequest(Request $request, $requestId)
    {
        $friendRequest = FriendRequest::where('id', $requestId)
            ->where('receiver_id', $request->user()->id)
            ->where('status', 'pending')
            ->first();

        if (!$friendRequest) {
            return response()->json([
                'success' => false,
                'message' => 'Friend request not found or already processed'
            ], 404);
        }

        $friendRequest->update(['status' => 'accepted']);

        return response()->json([
            'success' => true,
            'message' => 'Friend request accepted successfully',
            'data' => [
                'friend_request' => [
                    'id' => $friendRequest->id,
                    'sender_id' => $friendRequest->sender_id,
                    'receiver_id' => $friendRequest->receiver_id,
                    'status' => $friendRequest->status,
                    'updated_at' => $friendRequest->updated_at
                ]
            ]
        ]);
    }

    // Reject friend request
    public function rejectRequest(Request $request, $requestId)
    {
        $friendRequest = FriendRequest::where('id', $requestId)
            ->where('receiver_id', $request->user()->id)
            ->where('status', 'pending')
            ->first();

        if (!$friendRequest) {
            return response()->json([
                'success' => false,
                'message' => 'Friend request not found or already processed'
            ], 404);
        }

        $friendRequest->update(['status' => 'rejected']);

        return response()->json([
            'success' => true,
            'message' => 'Friend request rejected successfully'
        ]);
    }

    // Cancel sent friend request
    public function cancelRequest(Request $request, $requestId)
    {
        $friendRequest = FriendRequest::where('id', $requestId)
            ->where('sender_id', $request->user()->id)
            ->where('status', 'pending')
            ->first();

        if (!$friendRequest) {
            return response()->json([
                'success' => false,
                'message' => 'Friend request not found or already processed'
            ], 404);
        }

        $friendRequest->delete();

        return response()->json([
            'success' => true,
            'message' => 'Friend request cancelled successfully'
        ]);
    }

    // Get all friends
    public function getFriends(Request $request)
    {
        $user = $request->user();
        $friends = $user->friends()->get();

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

    // Get pending received friend requests
    public function getPendingRequests(Request $request)
    {
        $user = $request->user();
        $pendingRequests = $user->receivedFriendRequests()
            ->where('status', 'pending')
            ->with('sender:id,name,email,created_at')
            ->get()
            ->map(function($request) {
                return [
                    'id' => $request->id,
                    'sender' => $request->sender,
                    'created_at' => $request->created_at
                ];
            });

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

    // Get sent friend requests
    public function getSentRequests(Request $request)
    {
        $user = $request->user();
        $sentRequests = $user->sentFriendRequests()
            ->where('status', 'pending')
            ->with('receiver:id,name,email,created_at')
            ->get()
            ->map(function($request) {
                return [
                    'id' => $request->id,
                    'receiver' => $request->receiver,
                    'created_at' => $request->created_at
                ];
            });

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

    // Remove friend
    public function removeFriend(Request $request, $friendId)
    {
        $user = $request->user();

        $friendRequest = FriendRequest::where(function($query) use ($user, $friendId) {
            $query->where('sender_id', $user->id)
                  ->where('receiver_id', $friendId);
        })->orWhere(function($query) use ($user, $friendId) {
            $query->where('sender_id', $friendId)
                  ->where('receiver_id', $user->id);
        })->where('status', 'accepted')
        ->first();

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

        $friendRequest->delete();

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