<?php

namespace App\Http\Controllers;

use App\Http\Requests\SelectionSearchSearchRequest;
use App\Http\Resources\LeaseVariantListResource;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;

class LeaseVehicleController extends Controller
{
    public function __construct()
    {
        $this->middleware([
            'permission:edit-vehicles',
        ]);
    }

    public function index(SelectionSearchSearchRequest $request)
    {
        $perPage = min((int) $request->input('per_page', 15), 200);

        $vehicles = KeyloopLeaseVehicleVariant::query()
            ->setSortBy($request->input('sort_by', 'id_desc'))
            ->setFilters($request->input('filters', []))
            ->when($request->filled('selections'), fn ($query) => $query->setSelections($request->getSelections()))
            ->when(
                $request->filled('search_term'),
                fn ($query) => $query->where('name', 'like', '%' . $request->input('search_term') . '%')
            );

        return new LeaseVariantListResource($vehicles->paginate($perPage));
    }

    public function update(Request $request)
    {
        collect($request->input('vehicles'))->each(function ($vehicle) {
            KeyloopLeaseVehicleVariant::query()
                ->where('id', $vehicle['id'])
                ->update([
                    'featured' => $vehicle['featured']
                ]);
        });
    }
}
