<?php

namespace App\Http\Controllers;

use App\Models\BlogPost;
use App\Models\BlogComment;
use App\Models\Notification;
use App\Services\EmailService;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;

class BlogCommentController extends Controller
{
    public function store(Request $request, BlogPost $post): RedirectResponse
    {
        // Guest or logged in user
        $isGuest = !auth()->check();

        $rules = [
            'content'   => 'required|string|min:3|max:5000',
            'parent_id' => 'nullable|integer',
        ];

        if ($isGuest) {
            $rules['author_name']  = 'required|string|max:100';
            $rules['author_email'] = 'required|email|max:100';
        }

        $validated = $request->validate($rules);

        // parent_id varsa doğrula
        if (!empty($validated['parent_id'])) {
            $parentExists = BlogComment::where('id', $validated['parent_id'])
                ->where('post_id', $post->id)
                ->exists();
            if (!$parentExists) {
                $validated['parent_id'] = null;
            }
        }

        $comment = $post->comments()->create([
            'user_id'      => auth()->check() ? auth()->id() : null,
            'author_name'  => auth()->check() ? null : $validated['author_name'],
            'author_email' => auth()->check() ? null : $validated['author_email'],
            'author_ip'    => $request->ip(),
            'content'      => $validated['content'],
            'parent_id'    => $validated['parent_id'] ?? null,
            'is_approved'  => false, // Admin onayı gerekiyor
        ]);

        // ── Blog Comment Notifications ──────────────────────────────────
        $emailService = app(EmailService::class);
        
        // Notify post author about new comment
        if (auth()->check() && $post->user_id !== auth()->id()) {
            Notification::create([
                'user_id'      => $post->user_id,
                'type'         => 'blog_comment',
                'title'        => 'Yeni Yorum',
                'message'      => auth()->user()->name . ' yazınıza yorum yaptı: "' . Str::limit($validated['content'], 80) . '"',
                'link'         => route('blog.show', $post->slug) . '#comment-' . $comment->id,
                'is_read'      => false,
            ]);
            
            // Send email notification
            $emailService->sendBlogCommentEmail(
                $post->user,
                $post,
                $comment,
                'new_comment'
            );
        }

        // Notify parent comment author about reply
        if (!empty($validated['parent_id']) && auth()->check()) {
            $parentComment = BlogComment::find($validated['parent_id']);
            if ($parentComment && $parentComment->user_id && $parentComment->user_id !== auth()->id()) {
                Notification::create([
                    'user_id'      => $parentComment->user_id,
                    'type'         => 'blog_comment_reply',
                    'title'        => 'Yorum Yanıtı',
                    'message'      => auth()->user()->name . ' yorumunuza yanıt verdi.',
                    'link'         => route('blog.show', $post->slug) . '#comment-' . $comment->id,
                    'is_read'      => false,
                ]);
                
                // Send email notification
                $emailService->sendBlogCommentEmail(
                    $parentComment->user,
                    $post,
                    $comment,
                    'reply'
                );
            }
        }
        // ────────────────────────────────────────────────────────────────

        return redirect()->back()
            ->with('success', 'Yorumunuz alındı. Admin onayından sonra yayınlanacak.');
    }

    public function destroy(BlogComment $comment): RedirectResponse
    {
        if (!auth()->check()) {
            return redirect()->route('login');
        }

        // Kendi yorumunu veya admin ise silebilir
        if (auth()->id() !== $comment->user_id && !auth()->user()->isAdmin()) {
            abort(403);
        }

        $comment->delete();

        return redirect()->back()
            ->with('success', 'Yorum silindi.');
    }
}
