<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Notifications\SystemAlertNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class NotificationsController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:notifications.update')->only(['markRead', 'markAllRead']);
    }

    public function markRead(string $id)
    {
        $user = User::query()->findOrFail(Auth::id());

        $notification = $user->notifications()
            ->where('id', $id)
            ->firstOrFail();

        $notification->markAsRead();

        $redirectUrl = $notification->data['url'] ?? null;

        return $redirectUrl
            ? redirect()->to($redirectUrl)
            : redirect()->back();
    }

    public function markAllRead(Request $request)
    {
        $user = User::query()->findOrFail(Auth::id());
        $user->unreadNotifications->markAsRead();

        return redirect()->back();
    }

    public function poll(Request $request)
    {
        $user = User::query()->findOrFail(Auth::id());

        $notifications = $user->unreadNotifications()
            ->where('type', SystemAlertNotification::class)
            ->latest()
            ->limit(5)
            ->get();

        $items = $notifications
            ->map(fn ($n) => [
                'id' => $n->id,
                'title' => (string) ($n->data['title'] ?? ''),
                'body' => (string) ($n->data['body'] ?? ''),
                'created_at' => $n->created_at?->toIso8601String(),
            ])
            ->values()
            ->all();

        // Calculate chat unread
        $publicUnread = \App\Models\Message::whereNull('receiver_id')
            ->where('sender_id', '!=', $user->id)
            ->whereDoesntHave('reads', function ($q) use ($user) {
                $q->where('user_id', $user->id);
            })->count();

        $privateUnread = \App\Models\Message::where('receiver_id', $user->id)
            ->whereDoesntHave('reads', function ($q) use ($user) {
                $q->where('user_id', $user->id);
            })->count();

        $chat_unread = $publicUnread + $privateUnread;

        return response()->json([
            'items' => $items,
            'chat_unread' => $chat_unread,
        ]);
    }
}
