<?php

namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;

use App\Models\Notice;
use App\Models\User;
use Illuminate\Http\Request;

class NoticeController extends Controller
{
    public function index(Request $request)
    {
        $q = Notice::query()->with('creator');

        if ($s = $request->get('q')) {
            $q->where(function($w) use ($s){
                $w->where('title','like',"%{$s}%")
                  ->orWhere('body','like',"%{$s}%");
            });
        }

        $notices = $q->orderByDesc('id')->paginate(12)->withQueryString();
        return view('backend.notices.index', compact('notices'));
    }

    public function create()
    {
        return view('backend.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,
    ]);

    // সব ইউজারকে Unread হিসেবে অ্যাটাচ (read_at = null)
    // বড় ইউজার লিস্ট হলে মেমরি বাঁচাতে chunk ব্যবহার
    User::query()->select('id')->chunkById(1000, function($chunk) use ($notice) {
        $map = [];
        foreach ($chunk as $u) { $map[$u->id] = ['read_at' => null]; }
        // sync(..., false) = detach করবে না; শুধু নতুনদের attach করবে
        $notice->users()->sync($map, false);
    });

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


    public function show($id)
    {
        $notice = Notice::with('creator')->findOrFail($id);
        return view('backend.notices.show', compact('notice'));
    }

    public function edit($id)
    {
        $notice = Notice::findOrFail($id);
        return view('backend.notices.edit', compact('notice'));
    }

  public function update(Request $request, $id)
{
    $notice = Notice::findOrFail($id);

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

    $notice->update([
        'title' => $data['title'],
        'body'  => $data['body'] ?? null,
    ]);

    // আপডেটের সময় নতুন ইউজার যোগ হলে তাদেরকেও Unread হিসেবে attach করুন
    User::query()->select('id')->chunkById(1000, function($chunk) use ($notice) {
        $map = [];
        foreach ($chunk as $u) { $map[$u->id] = ['read_at' => null]; }
        // existing pivot গুলো (read_at সহ) টাচ করা হবে না; শুধু নতুনদের যোগ হবে
        $notice->users()->sync($map, false);
    });

    return redirect(url('/admin/notices'))->with('success','Notice updated.');
}

    public function destroy($id)
    {
        $notice = Notice::findOrFail($id);
        $notice->delete();
        return redirect(url('/admin/notices'))->with('success','Notice deleted.');
    }
}
