<?php

namespace App\Http\Controllers;

use App\Http\Resources\VehicleMoveRequestList;
use App\Http\Resources\VehicleMoveRequestView;
use Illuminate\Http\Request;
use Mtc\VehicleReservations\VehicleMoveRequest;

class VehicleMoveRequestController extends Controller
{
    public function index(Request $request): VehicleMoveRequestList
    {
        return new VehicleMoveRequestList(
            VehicleMoveRequest::query()
                ->with([
                    'vehicle' => fn ($query) => $query->withTrashed()->with('dealership'),
                    'fromDealership',
                    'toDealership',
                ])
                ->whereNotNull('paid_at')
                ->when(
                    $request->filled('dealership_id'),
                    fn ($query) => $query->where(function ($query) use ($request) {
                        $query->where('from_dealership_id', $request->input('dealership_id'))
                            ->orWhere('to_dealership_id', $request->input('dealership_id'));
                    })
                )
                ->when(
                    $request->filled('search_term'),
                    fn ($query) => $query->where(function ($query) use ($request) {
                        $term = '%' . $request->input('search_term') . '%';
                        $query->where('reference', 'like', $term)
                            ->orWhere('name', 'like', $term)
                            ->orWhere('email', 'like', $term)
                            ->orWhereHas(
                                'vehicle',
                                fn ($q) => $q->withTrashed()
                                    ->where('vrm_condensed', 'like', $term)
                                    ->orWhere('title', 'like', $term)
                            );
                    })
                )
                ->latest()
                ->paginate()
        );
    }

    public function show(VehicleMoveRequest $vehicleMoveRequest): VehicleMoveRequestView
    {
        return new VehicleMoveRequestView($vehicleMoveRequest);
    }

    public function destroy(Request $request, VehicleMoveRequest $vehicleMoveRequest): VehicleMoveRequestList
    {
        $vehicleMoveRequest->update(['status' => 'cancelled']);

        return $this->index($request);
    }
}
