<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function markAsRead($id)
    {
        $notification = auth()->user()->notifications()->findOrFail($id);
        $notification->markAsRead();

        // Check if there is a URL in the data to redirect to
        if (isset($notification->data['url'])) {
            return redirect($notification->data['url']);
        }

        return back();
    }

    public function markAllAsRead()
    {
        auth()->user()->unreadNotifications->markAsRead();
        return back();
    }

    public function fetchUnread()
    {
        $notifications = auth()->user()->unreadNotifications;
        
        $html = '';
        if ($notifications->count() > 0) {
            foreach ($notifications as $notification) {
                $html .= '<a href="' . route('notifications.read', $notification->id) . '" class="flex items-center px-4 py-3 border-b hover:bg-gray-100">';
                $html .= '  <div class="mx-3">';
                $html .= '      <p class="text-gray-600 text-sm font-semibold">' . ($notification->data['title'] ?? 'Notification') . '</p>';
                $html .= '      <p class="text-gray-500 text-xs">' . ($notification->data['message'] ?? '') . '</p>';
                $html .= '      <p class="text-gray-400 text-xs mt-1">' . $notification->created_at->diffForHumans() . '</p>';
                $html .= '  </div>';
                $html .= '</a>';
            }
        } else {
             $html .= '<div class="px-4 py-3 text-sm text-gray-500">No new notifications</div>';
        }

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