<?php

namespace App\Http\Controllers\V3\Dashboard;

use App\Exports\V3\RoadItemsProjects\OperatorCartableReport;
use App\Exports\V3\RoadItemsProjects\SupervisorCartableReport;
use App\Http\Controllers\Controller;
use App\Http\Requests\V3\RoadItemsProject\StoreRequest;
use App\Http\Requests\V3\RoadItemsProject\UpdateRequest;
use App\Http\Requests\V3\RoadItemsProject\VerifyBySupervisorRequest;
use App\Http\Traits\ApiResponse;
use App\Models\EdarateShahri;
use App\Models\InfoItem;
use App\Models\RoadItemsProject;
use App\Services\NominatimService;
use App\Services\Cartables\RoadItemTableService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class RoadItemsProjectController extends Controller
{
    use ApiResponse;
    /**
     * Display a listing of the resource.
     */
    public function supervisorIndex(Request $request, RoadItemTableService $roadItemTableService): JsonResponse
    {
        $data = $roadItemTableService->supervisorCartableReport($request);

        foreach ($data['data'] as $road_item) {
            if (Gate::allows('gate-supervise-road-item', $road_item)) {
                $road_item['can_supervise'] = 1;
            } else {
                $road_item['can_supervise'] = 0;
            }
        }

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

    public function verifyBySupervisor(VerifyBySupervisorRequest $request, RoadItemsProject $roadItemsProject): JsonResponse
    {
        $status_fa = $request->verify == 1 ? 'تایید شده' : 'عدم تایید';
        $user = auth()->user();

        $roadItemsProject->update([
            'status' => $request->verify,
            'status_fa' => $status_fa,
            'supervisor_id' => $user->id,
            'supervisor_name' => $user->name,
            'supervisor_description' => $request->description,
            'supervising_time' => now(),
        ]);

        $user->addActivityComplete(1149);

        return $this->successResponse();
    }

    public function restore(RoadItemsProject $roadItemsProject): JsonResponse
    {
        if ($roadItemsProject->status == 0) {
            return $this->errorResponse('امکان بازگردانی وضعیت این فعالیت وجود ندارد!');
        }

        $roadItemsProject->update([
            'status' => 0,
            'status_fa' => 'در حال بررسی',
            'supervisor_id' => null,
            'supervisor_description' => null,
            'supervising_time' => null,
            'supervisor_name' =>  null,
        ]);
        auth()->user()->addActivityComplete(1150);

        return $this->successResponse();
    }

    public function delete(RoadItemsProject $roadItemsProject): JsonResponse
    {
        if ($roadItemsProject->files()->exists()) {
            Storage::delete('public/'. $roadItemsProject->files[0]->path);
            Storage::delete('public/'. $roadItemsProject->files[1]->path);
            $roadItemsProject->files()->delete();
        }
        auth()->user()->addActivityComplete(1151);

        $roadItemsProject->delete();

        return $this->successResponse();
    }


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

    public function operatorIndex(Request $request, RoadItemTableService $roadItemTableService): JsonResponse
    {
        $data = $roadItemTableService->operatorCartableReport($request);
        return response()->json($data);
    }

    /**
     * Store a newly created resource in storage.
     * @throws ValidationException
     */
    public function store(StoreRequest $request, NominatimService $nominatimService): JsonResponse
    {
        $user = auth()->user();

        if ($user->edarate_ostani_id || is_null($user->city_id)) {
            return $this->errorResponse('امکان ثبت فعالیت برای ادارات استانی و ستادی وجود ندارد!');
        }

        if (is_null($user->edarate_shahri_id)) {
            return $this->errorResponse('اداره شهری برای شما در سامانه ثبت نشده است!');
        }

        $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;

        $attributes = [
            '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,
        ];

        $after_image = ($request->has('after_image') && $info_item->needs_image) ?
            $request->file('after_image') :
            null;

        $before_image = ($request->has('before_image') && $info_item->needs_image) ?
            $request->file('before_image') :
            null;

        $road_item = RoadItemsProject::store($user, $attributes, $before_image, $after_image, $request->observed_item_id);

        if ($road_item === -1) {
            return $this->errorResponse('اقدام مربوطه قبلا رسیدگی شده است.');
        }

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

        auth()->user()->addActivityComplete(1154);

        return $this->successResponse();
    }

    /**
     * Update the specified resource in storage.
     * @throws ValidationException
     */
    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')) {

                Storage::delete('public/'. $roadItemsProject->files[0]->path);

                $after = $request->file('after_image')->store('road_items_projects_new/after', 'public');
                $roadItemsProject->files[0]->update([
                    'path' => $after
                ]);
                // $roadItemsProject->files()->create(['path' => $after]);
                $urlAfter = "/var/www/rms/public/storage/{$after}";
                // \App\Helpers\Compress::resize($urlAfter);
            }
            if ($request->has('before_image')) {
                Storage::delete('public/'. $roadItemsProject->files[1]->path);

                $before = $request->file('before_image')->store('/road_items_projects_new/before', 'public');
                $roadItemsProject->files[1]->update([
                    'path' => $before
                ]);
                // $roadItemsProject->files()->create(['path' => $before]);
                $urlBefore = "/var/www/rms/public/storage/{$before}";
                // \App\Helpers\Compress::resize($urlBefore);
            }
        }

        $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);


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

        return $this->successResponse();
    }

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

    public function roadItemMachine(RoadItemsProject $roadItemsProject): JsonResponse
    {
        return $this->successResponse($roadItemsProject->cmmsMachines()->get(['cmms_machines.id', 'cmms_machines.machine_code', 'cmms_machines.car_name', 'cmms_machines.plak_number']));
    }

    public function roadItemRahdar(RoadItemsProject $roadItemsProject): JsonResponse
    {
        return $this->successResponse($roadItemsProject->rahdaran()->get(['rahdaran.id', 'rahdaran.name', 'rahdaran.code']));
    }

    public function roadItemFile(RoadItemsProject $roadItemsProject): JsonResponse
    {
        return $this->successResponse($roadItemsProject->files()->get(['path']));
    }
}
