<?php

namespace App\Services\Cartables\RoadObservation;

use App\Exceptions\ProhibitedAction;
use App\Facades\DataTable\DataTableFacade;
use App\Models\RoadObserved;
use Illuminate\Http\Request;

class SupervisorService
{
    /**
     * @throws \Throwable
     */
    public function index(Request $request)
    {
        $user = auth()->user();

        $fields = [
            'fk_RegisteredEventMessage', 'road_observeds.id', 'Title', 'road_observeds.created_at', 'StartTime_DateTime',
            'lat', 'lng', 'FeatureTypeTitle', 'Description', 'MobileForSendEventSms', 'rms_start_latlng',
            'rms_description', 'rms_status', 'rms_last_activity_fa', 'rms_last_activity', 'edarate_shahri_id',
            'road_observeds.province_id', 'province_fa', 'city_id', 'city_fa', 'edarate_shahri.name_fa',
            'status', 'status_fa', 'supervisor_description', 'supervising_time', 'image_after', 'image_before'
        ];

        if ($user->hasPermissionTo('show-fast-react')) {
            $query = RoadObserved::query()->leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
                ->whereNotNull('road_observeds.status')
                ->select($fields);
        }
        elseif ($user->hasPermissionTo('show-fast-react-province'))
        {
            throw_if(is_null($user->province_id), new ProhibitedAction('استانی برای شما در سامانه ثبت نشده است!'));

            $query = RoadObserved::query()->leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
                ->where('road_observeds.province_id', $user->province_id)
                ->whereNotNull('road_observeds.status')
                ->select($fields);
        }

        return DataTableFacade::run(
            $query,
            $request,
            allowedFilters: ['*'],
            allowedSortings: ['*']);
    }
}