<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Notification;
use Illuminate\Pagination\LengthAwarePaginator;

class NotificationTablesController extends Controller
{
    public function index(Request $request)
    {
        $data = Notification::query();
        $search = $request->input('search');
        if ($search) {
            $data->where('title', 'like', "%$search%");
        }
        $sortField = $request->input('_sort_by');
        $sortOrder = $request->input('_sort_order', 'asc') === 'asc' ? 'asc' : 'desc';
        if ($sortField) {
            $data->orderBy($sortField, $sortOrder);
        }
        $dateStart = $request->input('date_start');
        $dateEnd = $request->input('date_end');
        if ($dateStart && $dateEnd) {
            $data->whereBetween('created_at', [$dateStart, $dateEnd]);
        }
        $perPage = $request->input('page_size', 10);
        $currentPage = $request->input('page', 1);
        $paginatedData = $data->paginate($perPage);

        $columns = [
            ['title' => 'ID', 'dataIndex' => 'id'],
            ['title' => 'Title', 'dataIndex' => 'title'],
        ];
        $actions = [
            ['key' => 'edit', 'title' => 'Edit', 'icon' => 'edit'],
            ['key' => 'delete', 'title' => 'Delete', 'icon' => 'delete'],
        ];

        return view('notification-tables', compact('paginatedData', 'columns', 'actions'));
    }

    public function destroy($id)
    {
        Notification::find($id)->delete();
        return redirect()->back()->with('success', 'Notification deleted');
    }

    public function batchDestroy(Request $request)
    {
        $ids = $request->input('ids', []);
        Notification::whereIn('id', $ids)->delete();
        return redirect()->back()->with('success', 'Notifications deleted');
    }
}