<?php
namespace App\Http\Controllers;

use App\Models\Notice;
use App\Models\User;
use Illuminate\Http\Request;
use Carbon\Carbon;
class NoticeController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        // পেজে ঢুকলেই সব Unread -> Read
        $ids = $user->notices()->pluck('notices.id')->all();
        if ($ids) {
            $user->notices()
                ->wherePivotNull('read_at')
                ->updateExistingPivot($ids, ['read_at' => now()]);
        }

        // সব নোটিস নামিয়ে এনে গ্রুপিং
        $all = $user->notices()
            ->select('notices.id','title','body','notices.created_at')
            ->orderByDesc('notices.created_at')
            ->get();

        $today = $all->filter(fn($n) => $n->created_at->isToday());
        $yesterday = $all->filter(fn($n) => $n->created_at->isYesterday());
        $older = $all->filter(fn($n) => $n->created_at->isBefore(Carbon::yesterday()));

        // navbar-এ দেখানোর জন্য unreadCount এখন 0 হবে (কারণ read করে দিলাম)
        $unreadCount = 0;

        return view('frontend.notices.index', compact('today','yesterday','older','unreadCount'));
    }
    public function create() { return view('frontend.notices.create'); }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title' => ['required','string','max:255'],
            'body'  => ['nullable','string'],
        ]);

        $notice = Notice::create([
            'title' => $data['title'],
            'body'  => $data['body'] ?? null,
            'created_by' => $request->user()->id,
        ]);

        // Attach to all users as Unread
        $ids = User::pluck('id')->all();
        $notice->users()->sync(
            collect($ids)->mapWithKeys(fn($id)=>[$id=>['read_at'=>null]])->all(),
            false
        );

        return redirect()->back()->with('status','Notice published');
    }

    // AJAX: latest notices list (no reload)
    public function list(Request $request)
    {
        $items = $request->user()
            ->notices()
            ->select('notices.id','title','body','notices.created_at')
            ->take(30)
            ->get()
            ->map(fn($n)=>[
                'id'=>$n->id,
                'title'=>$n->title,
                'body'=>$n->body,
                'time'=>$n->created_at->diffForHumans(),
                'is_read'=>!is_null($n->pivot->read_at),
            ]);

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