<?php

namespace App\Http\Controllers\V2\Dashboard;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Models\ObservedItem;
use App\Models\RoadPatrol;
use Illuminate\Database\Eloquent\Builder;

class ObservedItemController extends Controller
{
    public function details(ObservedItem $observed_item)
    {
        return response()->json($observed_item);
    }

    public function searchByFilter(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'start_date' => 'date_format:Y-m-d',
            'end_date' => 'date_format:Y-m-d|after_or_equal:start_date',
            'road_patrol_id' => 'numeric',
            'item_id' => 'numeric',
        ], [], [
            'start_date' => 'ساعت شروع گشت',
            'end_date' => 'ساعت پایان گشت',
        ])->validate();

        $data = ObservedItem::whereNull('road_item_id')
            ->when($request->start_date, function (Builder $query) use ($request) {
                return $query->whereHas('roadPatrol', function (Builder $query) use ($request) {
                    $query->WhereBetween('start_time', [$request->start_date.' 00:00:00', $request->end_date.' 23:59:59'])->orWhereBetween('end_time', [$request->start_date.' 00:00:00', $request->end_date.' 23:59:59']);
                });
            })
            ->when($request->road_patrol_id, function (Builder $query) use ($request) {
                return $query->where('road_patrol_id', $request->road_patrol_id);
            })
            ->when($request->item_id, function (Builder $query) use ($request) {
                return $query->where('item_id', $request->item_id);
            })
            ->selectRaw('id as item, item_id, item_name, sub_item_id, sub_item_name, local_name')->get();

        // dd($data);
        if($data->isEmpty()) {
            abort(404);
        }

        return response()->json(
            $data
        );
    }
}
