<?php

namespace App\Http\Controllers;

use App\Models\ForumNotification;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;

class ForumNotificationController extends Controller
{
    /**
     * Display all notifications for the authenticated user.
     */
    public function index(Request $request): View
    {
        if (!auth()->check()) {
            abort(403);
        }

        $user = auth()->user();

        $notifications = ForumNotification::forUser($user->id)
            ->with(['fromUser', 'post', 'topic'])
            ->latest()
            ->paginate(20);

        // Get unread count
        $unreadCount = ForumNotification::unreadCount($user->id);

        return view('forum.notifications.index', compact('notifications', 'unreadCount'));
    }

    /**
     * Get unread notification count (AJAX).
     */
    public function unreadCount(): JsonResponse
    {
        if (!auth()->check()) {
            return response()->json(['count' => 0]);
        }

        $count = ForumNotification::unreadCount(auth()->id());

        return response()->json(['count' => $count]);
    }

    /**
     * Mark a specific notification as read.
     */
    public function markAsRead(ForumNotification $notification): JsonResponse
    {
        if (!auth()->check()) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        if ($notification->user_id !== auth()->id()) {
            return response()->json(['error' => 'Forbidden'], 403);
        }

        $notification->markAsRead();

        return response()->json(['success' => true]);
    }

    /**
     * Mark all notifications as read for the authenticated user.
     */
    public function markAllAsRead(): JsonResponse
    {
        if (!auth()->check()) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        ForumNotification::markAllAsRead(auth()->id());

        return response()->json(['success' => true]);
    }

    /**
     * Delete a specific notification.
     */
    public function delete(ForumNotification $notification): JsonResponse
    {
        if (!auth()->check()) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        if ($notification->user_id !== auth()->id()) {
            return response()->json(['error' => 'Forbidden'], 403);
        }

        $notification->delete();

        return response()->json(['success' => true]);
    }

    /**
     * Delete all read notifications.
     */
    public function deleteRead(): JsonResponse
    {
        if (!auth()->check()) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        ForumNotification::where('user_id', auth()->id())
            ->where('is_read', true)
            ->delete();

        return response()->json(['success' => true]);
    }
}
