<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\admin\Notification\StoreRequest;
use App\Http\Requests\admin\Notification\UpdateRequest;
use App\Models\Notification;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function index(Request $request)
    {
        $query = Notification::query();

        if ($request->filled('q')) {
            $q = $request->q;
            $query->where(function ($qry) use ($q) {
                $qry->where('title', 'like', "%{$q}%")
                    ->orWhere('description', 'like', "%{$q}%");
            });
        }

        $perPage = min(max((int) $request->input('per_page', 15), 10), 100);
        $notifications = $query->latest()->paginate($perPage)->withQueryString();

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

    public function create()
    {
        return view('admin.notifications.create');
    }

    public function store(StoreRequest $request)
    {
        Notification::create($request->validated());
        return redirect()->route('notifications.index');
    }

    public function edit(Notification $notification)
    {
        return view('admin.notifications.update', compact('notification'));
    }

    public function update(UpdateRequest $request, Notification $notification)
    {
        $notification->update($request->validated());
        return redirect()->route('notifications.index');
    }

    public function destroy(Notification $notification)
    {
        $notification->delete();
        return redirect()->route('notifications.index');
    }
}
