<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Comment;
use App\Models\Post;
use Illuminate\Support\Facades\Notification;
use App\Notifications\ReplyComment;

class CommentController extends Controller
{
    public function store(Request $request, Post $post)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'content' => 'required',
            'website' => 'nullable|url',
            'parent_id' => 'nullable|exists:comments,id'
        ]);

        // Create the new comment
        $comment = Comment::create([
            'post_id' => $post->id,
            'name' => $request->name,
            'email' => $request->email,
            'content' => $request->content,
            'website' => $request->website,
            'parent_id' => $request->parent_id,
            'active' => 1,
            'published_at' => now()
        ]);

        // If it's a reply, notify the original commenter
        if ($request->parent_id) {
            $parentComment = Comment::find($request->parent_id);
            if ($parentComment) {
                Notification::route('mail', $parentComment->email)
                    ->notify(new ReplyComment($parentComment, $comment));
            }
        }

        // Check if the request expects JSON (i.e., AJAX request)
        if ($request->expectsJson()) {
            return response()->json([
                'message' => 'Comment added successfully!',
                'comment' => $comment, // Keep for regular comments
                'reply' => $request->parent_id ? $comment : null // Ensure replies are explicitly returned
            ], 201);
        }

        // Redirect for normal form submissions
        return redirect()->route('view', $post->slug)->with('success', 'Comment added successfully!');
    }
}