<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Models\PostComment;
use App\Models\PostLike;
use App\Support\Notifier;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PostController extends Controller
{
    public function index()
    {
        $me        = auth()->user();
        $friendIds = $me->friendIds();
        $ids       = array_merge($friendIds, [$me->id]);

        $posts = Post::whereIn('user_id', $ids)
            ->with(['author', 'likes', 'comments.author'])
            ->latest()
            ->paginate(15);

        return view('feed.index', compact('posts'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'body'  => 'nullable|string|max:2000',
            'image' => 'nullable|image|max:5120',
        ]);

        if (!$request->filled('body') && !$request->hasFile('image')) {
            return back()->with('error', 'Escribe algo o adjunta una imagen.');
        }

        $imagePath = null;
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('posts', 'public');
        }

        Post::create([
            'user_id'    => auth()->id(),
            'body'       => $request->body,
            'image_path' => $imagePath,
        ]);

        return back()->with('success', 'Publicación creada.');
    }

    public function like(Post $post)
    {
        $me    = auth()->user();
        $liked = PostLike::where('user_id', $me->id)->where('post_id', $post->id)->first();

        if ($liked) {
            $liked->delete();
            $liked = false;
        } else {
            PostLike::create(['user_id' => $me->id, 'post_id' => $post->id]);
            $liked = true;

            // Notify post author (not if liking own post)
            if ($post->user_id !== $me->id) {
                $post->load('author');
                Notifier::send(
                    recipient: $post->author,
                    title:     $me->name . ' le dio Me gusta a tu publicación',
                    body:      $post->body ? \Str::limit($post->body, 60) : '',
                    icon:      'fa-heart',
                    color:     'danger',
                    url:       route('feed') . '#post-' . $post->id,
                );
            }
        }

        return response()->json([
            'liked' => $liked,
            'count' => $post->likes()->count(),
        ]);
    }

    public function comment(Request $request, Post $post)
    {
        $request->validate(['body' => 'required|string|max:500']);

        $me      = auth()->user();
        $comment = PostComment::create([
            'user_id' => $me->id,
            'post_id' => $post->id,
            'body'    => $request->body,
        ]);

        $comment->load('author');

        // Notify post author (not if commenting on own post)
        if ($post->user_id !== $me->id) {
            $post->load('author');
            Notifier::send(
                recipient: $post->author,
                title:     $me->name . ' comentó en tu publicación',
                body:      \Str::limit($request->body, 60),
                icon:      'fa-comment',
                color:     'info',
                url:       route('feed') . '#post-' . $post->id,
            );
        }

        return response()->json([
            'id'         => $comment->id,
            'body'       => $comment->body,
            'author'     => $comment->author->name,
            'avatar'     => $comment->author->profile_photo_url,
            'created_at' => $comment->created_at->diffForHumans(),
        ]);
    }

    public function destroy(Post $post)
    {
        abort_unless($post->user_id === auth()->id(), 403);

        if ($post->image_path) {
            Storage::disk('public')->delete($post->image_path);
        }

        $post->delete();

        return back()->with('success', 'Publicación eliminada.');
    }
}
