<?php

namespace App\Services\Cartables\RoadItem;

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

class SupervisorService
{
    /**
     * @throws Throwable
     */
    public function dataTable(Request $request, $loadRelations = false)
    {
        $user = auth()->user();
        $query = null;

        if ($user->hasPermissionTo('show-road-item-supervise-cartable')) {
            $query = RoadItemsProject::query()
                ->where('is_new', 1)
                ->when($loadRelations, fn ($query) => $query->with(['rahdaran:id,name,code', 'cmmsMachines:id,machine_code,car_name,plak_number']));
        }
        elseif ($user->hasPermissionTo('show-road-item-supervise-cartable-province')) {
            throw_if(is_null($user->province_id), new ProhibitedAction('استانی برای شما در سامانه ثبت نشده است!'));
            $query = RoadItemsProject::query()
                ->where('is_new', 1)
                ->where('province_id', auth()->user()->province_id)
                ->when($loadRelations, fn ($query) => $query->with(['rahdaran:id,name,code', 'cmmsMachines:id,machine_code,car_name,plak_number']));
        }

        return DataTableFacade::run(
            $query,
            $request,
            allowedFilters: ['*'],
            allowedSortings: ['*'],
            allowedSelects: [
                'id', 'province_fa', 'edarat_name', 'item', 'item_fa', 'sub_item',
                'sub_item_fa', 'sub_item_data', 'unit_fa', 'start_lat', 'start_lng',
                'end_lat', 'end_lng', 'activity_date_time', 'created_at', 'status_fa', 'status'
            ]
        );
    }
}