<?php

namespace App\Http\Controllers\V3\Dashboard;

use App\Facades\DataTable\DataTableFacade;
use App\Http\Controllers\Controller;
use App\Http\Requests\V3\ObservedItem\StoreRequest;
use App\Http\Traits\ApiResponse;
use App\Models\InfoItem;
use App\Models\ObservedItem;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class ObservedItemController extends Controller
{
    use ApiResponse;
    public function show(ObservedItem $observedItem): JsonResponse
    {
        return $this->successResponse($observedItem);
    }

    public function filter(Request $request): JsonResponse
    {
        $columns = array(
            'id', 'item_id', 'road_patrol_id', 'roadPatrol.start_time', 'roadPatrol.end_time',
        );

        $allowedFilters = $columns;
        $allowedSortings = $columns;

        $data = ObservedItem::query()->whereNull('road_item_id');

        $dataTable = DataTableFacade::run(
            $data,
            $request,
            allowedFilters: $allowedFilters,
            allowedSortings: $allowedSortings
        );

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

    /**
     * @throws ValidationException
     */
    public function store(StoreRequest $request): jsonResponse
    {
        foreach ($request->observed_items as $index => $item) {
            $info_item = InfoItem::query()->where('item', $item['item_id'])
                ->where('sub_item', $item['sub_item_id'])
                ->firstOrFail();

            $start = explode(',', $item['start_point']);
            $priority = [
                1 => 'عادی',
                2 => 'فوری',
                3 => 'آنی',
            ];

            $data = [
                'road_patrol_id' => $request->road_patrol_id,
                'item_id' => $info_item->item,
                'item_name' => $info_item->item_str,
                'sub_item_id' => $info_item->sub_item,
                'sub_item_name' => $info_item->sub_item_str,
                'description' => $item['description'] ?? null,
                'start_lat' => $start[0],
                'start_lon' => $start[1],
                'priority' => $item['instant_action'] == 0 ? $item['priority'] : null,
                'priority_fa' => $item['instant_action'] ? $priority[$item['priority']] : null,
            ];

            if ($item['instant_action'] == 1) {
                $item_end_coordinates = null;

                if ($info_item->needs_end_point) {
                    if (!isset($item['end_point'])) {
                        throw ValidationException::withMessages([
                            "observed_items.$index.end_point" => __('validation.required', ['attribute' => 'end_point']),
                        ]);
                    }

                    $item_end_coordinates = explode(',', $item['end_point']);

                    $data['end_lat'] = $item_end_coordinates[0];
                    $data['end_lon'] = $item_end_coordinates[1];
                }
            }
            DB::transaction(function () use ($data) {
                ObservedItem::query()->create($data);
            });
        }

        return $this->successResponse();
    }
}
