<?php

namespace App\Services\Menu;

use App\Models\MenuList;

class MenuListService
{
    public function list(array $filters = [])
    {
        return MenuList::query()
            ->when(
                !empty($filters['search']),
                fn($q) => $q->where(function ($x) use ($filters) {
                    $x->where('name', 'ILIKE', "%{$filters['search']}%")
                        ->orWhere('slug', 'ILIKE', "%{$filters['search']}%")
                        ->orWhere('url', 'ILIKE', "%{$filters['search']}%");
                })
            )
            ->when(
                isset($filters['is_active']) && $filters['is_active'] !== '',
                fn($q) => $q->where(
                    'is_active',
                    filter_var($filters['is_active'], FILTER_VALIDATE_BOOLEAN)
                )
            )
            ->latest('id')
            ->paginate($filters['per_page'] ?? 10);
    }

    public function create(array $data): MenuList
    {
        return MenuList::create($data);
    }

    public function update(MenuList $menuList, array $data): MenuList
    {
        $menuList->update($data);

        return $menuList->fresh();
    }

    public function delete(MenuList $menuList): bool
    {
        return $menuList->delete();
    }
}
