<?php

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

use App\Exceptions\ProhibitedAction;
use App\Exports\V3\RoadItemsProjects\OperatorCartableReport;
use App\Facades\File\FileFacade;
use App\Http\Controllers\Controller;
use App\Http\Requests\V3\RoadItem\Operator\StoreRequest;
use App\Http\Requests\V3\RoadItem\Operator\UpdateRequest;
use App\Http\Traits\ApiResponse;
use App\Models\EdarateShahri;
use App\Models\InfoItem;
use App\Models\ObservedItem;
use App\Models\RoadItemsProject;
use App\Services\Cartables\RoadItem\OperatorService;
use App\Services\NominatimService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Throwable;

class OperatorController extends Controller
{
    use ApiResponse;
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request, OperatorService $operatorService): JsonResponse
    {
        $data = $operatorService->dataTable($request);
        return response()->json($data);
    }

    public function excel(Request $request, OperatorService $operatorService): BinaryFileResponse
    {
        $name = 'گزارش از کارتابل عملیات فعالیت روزانه ' . verta()->now()->format('Y-m-d H:i') . '.xlsx';
        $data = $operatorService->dataTable($request, true);
        return Excel::download(new OperatorCartableReport($data['data']), $name);
    }

    /**
     * Store a newly created resource in storage.
     * @throws Throwable
     */
    public function store(StoreRequest $request, NominatimService $nominatimService): JsonResponse
    {
        $info_item = InfoItem::query()->where('item', $request->item_id)
            ->where('sub_item', $request->sub_item_id)
            ->firstOrFail();

        if ($info_item->needs_end_point && !$request->end_point) {
            throw ValidationException::withMessages([
                'end_point' => __('validation.required', ['attribute' => 'end_point']),
            ]);
        }

        if ((!$request->before_image || !$request->after_image) && $info_item->needs_image) {
            throw ValidationException::withMessages([
                'before_image' => __('validation.required', ['attribute' => 'before_image']),
                'after_image' => __('validation.required', ['attribute' => 'after_image']),
            ]);
        }

        $start_coordinates = explode(',', $request->start_point);
        $end_coordinates = $info_item->needs_end_point ? explode(',', $request->end_point) : null;

        DB::transaction(function () use ($request, $nominatimService, $start_coordinates, $end_coordinates, $info_item) {
            $user = auth()->user();
            $road_item = RoadItemsProject::query()->create([
                'user_id' => $user->id,
                'start_lat' => $start_coordinates[0],
                'start_lng' => $start_coordinates[1],
                'end_lat' => $end_coordinates ? $end_coordinates[0] : null,
                'end_lng' => $end_coordinates ? $end_coordinates[1] : null,
                'item' => $info_item->item,
                'item_fa' => $info_item->item_str,
                'sub_item' => $info_item->sub_item,
                'sub_item_fa' => $info_item->sub_item_str,
                'sub_item_data' => $request->amount,
                'province_id' => $user->province_id,
                'province_fa' => $user->province_fa,
                'city_id' => $user->city_id,
                'city_fa' => $user->city_fa,
                'user_name' => $user->name,
                'start_way_id' => $nominatimService->get_way_id_from_nominatim($start_coordinates[0], $start_coordinates[1]),
                'end_way_id' => $end_coordinates ? $nominatimService->get_way_id_from_nominatim($end_coordinates[0], $end_coordinates[1]) : null,
                'unit_fa' => $info_item->sub_item_unit,
                'created_at_fa' => verta(\Carbon\Carbon::now())->format('Y-m-d H:i:s'),
                'info_id' => $info_item->id,
                'status' => 0,
                'status_fa' => 'در حال بررسی',
                'edarat_id' => $user->edarate_shahri_id,
                'edarat_type' => EdarateShahri::class,
                'edarat_name' => $user->edarate_shahri_name,
                'activity_date' => $request->activity_date,
                'activity_time' => $request->activity_time,
                'activity_date_time' => $request->activity_date." ".$request->activity_time,
                'is_new' => 1,
            ]);

            if ($request->has('after_image')) {
                $road_item->files()->create([
                    'path' => FileFacade::save($request->file('after_image'),
                        "/road_items_projects_new/{$road_item->id}/after")
                ]);
            }
            if ($request->has('before_image')) {
                $road_item->files()->create([
                    'path' => FileFacade::save($request->file('before_image'),
                        "/road_items_projects_new/{$road_item->id}/before")
                ]);
            }

            throw_if(ObservedItem::query()->where('id', $request->observed_item_id)->whereNotNull('road_item_id')->exists(),
                new ProhibitedAction('اقدام مربوطه قبلا رسیدگی شده است.')
            );

            $road_item->rahdaran()->attach($request->rahdaran_id);
            $road_item->cmmsMachines()->attach($request->machines_id);
            $road_item->missions()->attach($request->mission_id);

            $user->addActivityComplete(1154);
        });

        return $this->successResponse();
    }

    /**
     * Display the specified resource.
     */
    public function show(RoadItemsProject $roadItemsProject): JsonResponse
    {
        return $this->successResponse($roadItemsProject);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateRequest $request, RoadItemsProject $roadItemsProject): JsonResponse
    {
        $info_item = InfoItem::query()->where('item', $roadItemsProject->item)
            ->where('sub_item', $roadItemsProject->sub_item)
            ->firstOrFail();

        $start_coordinates = explode(',', $request->start_point);
        $end_coordinates = null;

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

            $end_coordinates = explode(',', $request->end_point);
        }

        if ($info_item->needs_image) {
            if ($request->has('after_image')) {
                FileFacade::delete($roadItemsProject->files[0]->path, true);
                $roadItemsProject->files[0]->update([
                    'path' => FileFacade::save($request->file('after_image'),
                        "/road_items_projects_new/{$roadItemsProject->id}/after")
                ]);
            }
            if ($request->has('before_image')) {
                FileFacade::delete($roadItemsProject->files[1]->path, true);
                $roadItemsProject->files[1]->update([
                    'path' => FileFacade::save($request->file('before_image'),
                        "/road_items_projects_new/{$roadItemsProject->id}/before")
                ]);
            }
        }

        DB::transaction(function () use ($roadItemsProject, $start_coordinates, $end_coordinates, $request) {
            $roadItemsProject->update([
                'start_lat' => $start_coordinates[0],
                'start_lng' => $start_coordinates[1],
                'end_lat' => $end_coordinates ? $end_coordinates[0] : null,
                'end_lng' => $end_coordinates ? $end_coordinates[1] : null,
                'sub_item_data' => $request->amount,
                'status' => 0,
                'status_fa' => 'در حال بررسی',
            ]);

            $roadItemsProject->rahdaran()->sync($request->rahdaran_id);
            $roadItemsProject->cmmsMachines()->sync($request->machines_id);
            $roadItemsProject->missions()->sync($request->mission_id);


            auth()->user()->addActivityComplete(1155);
        });

        return $this->successResponse();
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(RoadItemsProject $roadItemsProject): JsonResponse
    {
        DB::transaction(function () use ($roadItemsProject) {
            if ($roadItemsProject->files()->exists()) {
                FileFacade::deleteDirectory("/road_items_projects_new/{$roadItemsProject->id}");
                $roadItemsProject->files()->delete();
            }
            auth()->user()->addActivityComplete(1151);

            $roadItemsProject->delete();
        });

        return $this->successResponse();
    }
}
