<?php

namespace App\Http\Controllers\V3\Dashboard\RoadPatrol;

use App\Http\Controllers\Controller;
use App\Http\Traits\ApiResponse;
use App\Models\RoadObserved;
use App\Models\RoadPatrol;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;


class DetailController extends Controller
{
    use ApiResponse;

    public function map(Request  $request): JsonResponse
    {
        $province = $request->province_id;
        $edare_shahri = $request->edare_shahri_id;
        $status = $request->status;
        $rms_status = $request->rms_status;

        if ($request->from_date && $request->date_to) {
            $date_from = $request->from_date.' 00:00:00';
            $date_to = $request->date_to.' 23:59:59';
        } else {
            $date_from = Date('Y-m-d');
            $date_to = new \DateTime('tomorrow');
            $date_to = $date_to->format('Y-m-d');
        }

        $projects = RoadObserved::query()->select(['id', 'lng', 'lat','status'])
            ->whereBetween('created_at', [$date_from, $date_to])
            ->when($province, function ($query) use ($province) {
                return $query->where('province_id', '=', $province);
            })
            ->when($rms_status, function ($query) use ($rms_status) {
                if ($rms_status == 2) {
                    return $query->where('rms_status', '<>', 0);
                } else {
                    return $query->where('rms_status', '=', 0);
                }
            })
            ->when($edare_shahri, function ($query) use ($edare_shahri) {
                return $query->where('edarate_shahri_id', '=', $edare_shahri);
            })
            ->when($status, function ($query) use ($status) {
                return $query->where('status', '=', $status);
            })
            ->get();
        return $this->successResponse($projects);
    }

    public function show(RoadPatrol $roadPatrol): JsonResponse
    {
        return $this->successResponse($roadPatrol);
    }

    public function machines(RoadPatrol $roadPatrol): JsonResponse
    {
        return $this->successResponse($roadPatrol->cmmsMachines()->get(['cmms_machines.id', 'cmms_machines.machine_code', 'cmms_machines.car_name', 'cmms_machines.plak_number']));
    }

    public function rahdaran(RoadPatrol $roadPatrol): JsonResponse
    {
        return $this->successResponse($roadPatrol->rahdaran()->get(['rahdaran.id', 'rahdaran.name', 'rahdaran.code']));
    }
}
