<?php

namespace App\Http\Controllers;

use App\Models\Friendship;
use App\Models\User;
use App\Support\Notifier;
use Illuminate\Http\Request;

class FriendshipController extends Controller
{
    public function index()
    {
        $requests = auth()->user()
            ->receivedFriendRequests()
            ->where('status', 'pending')
            ->with('sender')
            ->latest()
            ->get();

        return view('friendships.index', compact('requests'));
    }

    public function send(User $user)
    {
        $me = auth()->user();

        if ($me->id === $user->id) {
            return back()->with('error', 'No puedes enviarte una solicitud a ti mismo.');
        }

        if ($me->friendshipWith($user)) {
            return back()->with('error', 'Ya existe una relación con este usuario.');
        }

        Friendship::create([
            'sender_id'   => $me->id,
            'receiver_id' => $user->id,
            'status'      => 'pending',
        ]);

        Notifier::send(
            recipient: $user,
            title:     $me->name . ' te envió una solicitud de amistad',
            icon:      'fa-user-plus',
            color:     'primary',
            url:       route('friendships.index'),
        );

        return back()->with('success', 'Solicitud de amistad enviada.');
    }

    public function accept(Friendship $friendship)
    {
        abort_unless($friendship->receiver_id === auth()->id(), 403);

        $friendship->update(['status' => 'accepted']);
        $friendship->load('receiver');

        Notifier::send(
            recipient: $friendship->sender,
            title:     $friendship->receiver->name . ' aceptó tu solicitud de amistad',
            icon:      'fa-user-check',
            color:     'success',
            url:       route('social.profile', $friendship->receiver),
        );

        return back()->with('success', 'Solicitud aceptada.');
    }

    public function destroy(Friendship $friendship)
    {
        $me = auth()->id();
        abort_unless(
            $friendship->sender_id === $me || $friendship->receiver_id === $me,
            403
        );

        $friendship->delete();

        return back()->with('success', 'Solicitud eliminada.');
    }

    // AJAX desde búsqueda/perfil
    public function toggle(User $user)
    {
        $me = auth()->user();

        if ($me->id === $user->id) {
            return response()->json(['error' => 'No permitido'], 422);
        }

        $existing = $me->friendshipWith($user);

        if ($existing) {
            $existing->delete();
            return response()->json(['status' => 'none']);
        }

        Friendship::create([
            'sender_id'   => $me->id,
            'receiver_id' => $user->id,
            'status'      => 'pending',
        ]);

        Notifier::send(
            recipient: $user,
            title:     $me->name . ' te envió una solicitud de amistad',
            icon:      'fa-user-plus',
            color:     'primary',
            url:       route('friendships.index'),
        );

        return response()->json(['status' => 'pending']);
    }
}
