<?php

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

use App\Enums\HarimStates;
use App\Http\Controllers\Controller;
use App\Http\Requests\V3\Dashboard\Harim\PanjareVahed\GetAccessRoadRequest;
use App\Http\Requests\V3\Dashboard\Harim\PanjareVahed\ReceiveNewRequest;
use App\Http\Traits\ApiResponse;
use App\Models\City;
use App\Models\Harim;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

class PanjareVahedController extends Controller
{
    use ApiResponse;

    public function receiveNewRequest(ReceiveNewRequest $request)
    {
        try {
            $city = City::query()
                ->whereRaw("ST_Contains(
                    geometry, 
                    ST_SRID(ST_GeomFromText('POINT($request->lng $request->lat)'), 4326))"
                )
                ->firstOrFail(['id', 'name_fa', 'province_id']);
        }
        catch (ModelNotFoundException $exception){
            $city = City::query()
                ->orderByRaw("ST_Distance(
                    geometry, 
                    ST_SRID(ST_GeomFromText('POINT($request->lng $request->lat)'), 4326)
                    ) ASC"
                )
                ->first(['id', 'name_fa', 'province_id']);
        }

        $state = HarimStates::BARESI_EDARE_SHAHRESTAN->value;

        Harim::query()->create([
            'state_id' => $state,
            'state_name' => HarimStates::name($state),
            'panjare_vahed_id' => $request->id,
            'national_id' => $request->national_id,
            'phone_number' => $request->phone_number,
            'request_date' => $request->request_date,
            'province_id' => $city->province_id,
            'province_name' => $city->province()->first()->name_fa,
            'city_id' => $city->id,
            'city_name' => $city->name,
            'edareh_shahri_id' => $city->edarateShahri()->first()->id,
            'requested_organization' => $request->organization,
            'plan_group' => $request->plan_group,
            'plan_title' => $request->plan_title,
            'worksheet_id' => $request->worksheet_id,
            'response_options' => json_encode($request->response_options),
            'isic' => $request->isic,
            'primary_area' => $request->primary_area,
        ]);

        return $this->successResponse([
            'city' => $city->edarateShahri()->first()->name_fa,
            'province' => $city->province()->first()->name_fa,
        ]);
    }

    public function getAccessRoad(GetAccessRoadRequest $request)
    {
        $state = HarimStates::BARESI_FILE_APLODE_SHODE_TAVASOTE_DAFTAR_HARIM->value;

        Harim::query()
            ->firstWhere('panjare_vahed_id', '=', $request->panjare_vahed_id)
            ->update([
            'state_id' => $state,
            'state_name' => HarimStates::name($state),
            'access_road' => $request->access_road,
        ]);

        return $this->successResponse();
    }
}
