<?php

namespace App\Http\Controllers\V2\Dashboard;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Request;
use App\Facades\Sms\Sms;
use Illuminate\Support\Facades\Gate;
use App\Facades\Otp\Otp;
use Carbon\Carbon;
use App\Models\RoadObserved;
use App\Models\RoadPatrol;
use App\Models\RoadItemsProject;
use App\Models\EdarateShahri;
use App\Models\InfoItem;
use App\Services\NominatimService;
use App\Exports\V2\RoadPatrol\OperatorCartableExport;
use App\Exports\V2\RoadPatrol\SupervisorCartableExport;

class RoadPatrolProjectController extends Controller
{
    /**
     * Supervisor(Begin)
    */
    public function supervisorCartable()
    {
        if (!auth()->user()->can('show-road-patrol-supervise-cartable') && !auth()->user()->can('show-road-patrol-supervise-cartable-province')) {
            abort(403);
        }
        auth()->user()->addActivityComplete(1143);

        return view('version2.dashboard_pages.road_patrols.supervise_cartable');
    }

    public function supervisorShow(Request $request)
    {
        $fields = ['id', 'start_lat', 'start_lon', 'end_lat', 'end_lon', 'operator_id', 'operator_name', 'officer_plaque',
                   'officer_phone_number', 'officer_name', 'supervisor_description', 'supervising_time', 'supervisor_name', 'status', 'status_fa', 'distance',
                   'province_id', 'province_fa', 'edare_id', 'edare_name', 'start_time', 'end_time','description'];

        $aliases = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];

        $selectRaw = makeSelectQuery($fields, $aliases);

        if (auth()->user()->can('show-road-patrol-supervise-cartable')) {
            $query = RoadPatrol::selectRaw($selectRaw);
        } elseif (auth()->user()->can('show-road-patrol-supervise-cartable-province')) {
            if (is_null(auth()->user()->province_id)) {
                return response()->json([
                    'message' => 'استانی برای شما در سامانه ثبت نشده است!'
                ], 400);
            }

            $query = RoadPatrol::where('province_id', auth()->user()->province_id)
                                    //  ->where(function ($query) {
                                    //      $query->where('status', 0)
                                    //          ->orWhere('supervisor_id', auth()->user()->id);
                                    //  })
                                     ->selectRaw($selectRaw);
        } else {
            return response()->json([
                'message' => 'access to requested resource is forbidden.'
            ], 403);
        }

        $road_patrols = processDataTable($request, '', $fields, $query);
        $road_patrols['data']->map(function ($road_patrol) {
            if(Gate::allows('gate-supervise-road-item', $road_patrol)) {
                $road_patrol['can_supervise'] = 1;
            } else {
                $road_patrol['can_supervise'] = 0;
            }
        });

        return response()->json(
            $road_patrols,
            $road_patrols['status'],
        );
    }

    public function delete(Request $request, RoadPatrol $road_patrol)
    {
        $request->validate([
            'type' => 'required|in:1,2' // {1 = > partial , 2 => complete}
        ]);

        if ($request->type == 1) {
            if (! auth()->user()->can('partial-delete-road-patrol')) {
                return response()->json([
                    'message' => 'access to requested resource is forbidden.'
                ], 403);
            }

            try {
                \DB::transaction(function () use ($road_patrol) {
                    $road_patrol->observedItems()->delete();
                    $road_patrol->delete();
                });
            } catch (\Throwable $th) {
                throw $th;
            }

        } else {
            if (! auth()->user()->can('complete-delete-road-patrol')) {
                return response()->json([
                    'message' => 'access to requested resource is forbidden.'
                ], 403);
            }

            try {
                \DB::transaction(function () use ($road_patrol) {
                    if ($road_patrol->observedItems) {
                        foreach ($road_patrol->observedItems as $index => $observed_item) {
                            if ($observed_item->roadItemProject) {
                                $road_item = $observed_item->roadItemProject;

                                if ($road_item->files()->exists()) {
                                    Storage::delete('public/'. $road_item->files[0]->path);
                                    Storage::delete('public/'. $road_item->files[1]->path);
                                    $road_item->files()->delete();
                                }

                                $road_item->delete();
                            }

                            $observed_item->delete();
                        }
                    }
                    auth()->user()->addActivityComplete(1144);

                    $road_patrol->delete();
                });
            } catch (\Throwable $th) {
                throw $th;
            }
        }

        return response()->json([
            'message' => 'succussful'
        ]);
    }

    public function supervisorCartableReport(Request $request)
    {
        $name = 'گزارش از کارتابل ارزیابی گشت راهداری ' . verta()->now()->format('Y-m-d H:i') . '.xlsx';
        return Excel::download(new SupervisorCartableExport($request->id, $request->fromDate, $request->toDate, $request->province_id, $request->edare_id), $name);
    }

    /**
     * Supervisor(End)
    */

    /**
     * Operator(Begin)
    */
    public function operatorCartable()
    {
        if (!auth()->user()->hasPermissionTo('add-road-patrol')) {
            abort(403);
        }

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

        return view('version2.dashboard_pages.road_patrols.operation_cartable');
    }

    public function operatorCreateView()
    {
        if (!auth()->user()->hasPermissionTo('add-road-patrol')) {
            abort(403);
        }

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

        return view('version2.dashboard_pages.road_patrols.operation_create');
    }

    public function operatorShow(Request $request)
    {
        if (!auth()->user()->can('add-road-patrol')) {
            return response()->json([
                'message' => 'access to requested resource is forbidden.'
            ], 403);
        }

        $fields = ['id', 'start_lat', 'start_lon', 'end_lat', 'end_lon', 'officer_plaque',
                   'officer_phone_number', 'officer_name', 'supervisor_description', 'supervising_time', 'supervisor_name', 'status', 'status_fa', 'distance',
                   'start_time', 'end_time'];

        $aliases = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];

        $selectRaw = makeSelectQuery($fields, $aliases);

        $query = RoadPatrol::where('operator_id', auth()->user()->id)
                                 ->selectRaw($selectRaw);

        $data = processDataTable($request, '', $fields, $query);
        return response()->json(
            $data,
            $data['status'],
        );
    }

    public function store(Request $request, NominatimService $nominatimService)
    {
        if (!auth()->user()->hasPermissionTo('add-road-patrol')) {
            return response()->json([
                'message' => 'access to the requested resource is forbidden.'
            ], 403);
        }

        if (Auth::user()->edarate_ostani_id || is_null(Auth::user()->city_id)) {
            return response()->json([
                        'message' => 'امکان ثبت فعالیت برای ادارات استانی وجود ندارد!'
                    ], 400);
        }

        if (is_null(Auth::user()->edarate_shahri_id)) {
            return response()->json([
                'message' => 'اداره شهری برای شما در سامانه ثبت نشده است!'
            ], 400);
        }

        $validator = Validator::make($request->all(), [
            'start_point' => 'required',
            'end_point' => 'required',
            'distance' => 'numeric',
            'officer_name' => 'required',
            'officer_plaque' => 'required',
            'officer_phone_number' => 'required|digits:11',
            'start_time' => 'required|date_format:Y-m-d H:i',
            'end_time' => 'required|date_format:Y-m-d H:i|after:start_time',
            'description' => 'string',

            'observed_items' => 'array',
            'observed_items.*.item_id' => 'required|integer',
            'observed_items.*.sub_item_id' => 'required|integer',
            'observed_items.*.local_name' => 'required',
            'observed_items.*.description' => '',
            'observed_items.*.instant_action' => 'required|in:0,1',

            // road item projects fields
            'observed_items.*.start_point' => 'required',
            'observed_items.*.end_point' => '',
            'observed_items.*.amount' => 'numeric',
            'observed_items.*.before_image' => 'image|max:4096',
            'observed_items.*.after_image' => 'image|max:4096',
            'observed_items.*.priority' => 'integer|in:1,2,3',
            'observed_items.*.priority_fa' => 'string',
        ], [], [
            'start_time' => 'ساعت شروع گشت',
            'end_time' => 'ساعت پایان گشت',
        ])->validate();

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

        $edare_id = auth()->user()->edarate_shahri_id ?? auth()->user()->edarate_ostani_id;
        $edare_name = auth()->user()->edarate_shahri_id ? auth()->user()->edarate_shahri_name : auth()->user()->edarate_ostani_name;

        try {
            $road_patrol = \DB::transaction(function () use ($request, $start_coordinates, $end_coordinates, $edare_id, $edare_name, $nominatimService) {
                if (!$request->observed_items && !$request->description) {
                    throw ValidationException::withMessages([
                        "description" => __('validation.required', ['attribute' => 'description']),
                    ]);
                }

                $road_patrol = RoadPatrol::create([
                    'start_lat' => $start_coordinates[0],
                    'start_lon' => $start_coordinates[1],
                    'end_lat' => $end_coordinates[0],
                    'end_lon' => $end_coordinates[1],
                    'officer_name' => $request->officer_name,
                    'officer_phone_number' => $request->officer_phone_number,
                    'officer_plaque' => $request->officer_plaque,
                    'operator_id' => auth()->user()->id,
                    'operator_name' => auth()->user()->name,
                    'province_id' => auth()->user()->province_id,
                    'province_fa' => auth()->user()->province_fa,
                    'city_id' => auth()->user()->city_id,
                    'city_fa' => auth()->user()->city_fa,
                    'edare_id' => $edare_id,
                    'edare_name' => $edare_name,
                    'start_way_id' => $nominatimService->get_way_id_from_nominatim($start_coordinates[0], $start_coordinates[1]),
                    'end_way_id' => $nominatimService->get_way_id_from_nominatim($end_coordinates[0], $end_coordinates[1]),
                    'status' => 0,
                    'status_fa' => 'در حال بررسی',
                    'distance' => $request->distance,
                    'start_time' => $request->start_time,
                    'end_time' => $request->end_time,
                    'description' => $request->description ?? null,
                ]);

                if ($request->observed_items) {
                    foreach ($request->observed_items as $index => $item) {
                        $info_item = InfoItem::where('item', $item['item_id'])
                                             ->where('sub_item', $item['sub_item_id'])
                                             ->firstOrFail();

                        $item_start_coordinates = explode(',', $item['start_point']);

                        $observed_item = $road_patrol->observedItems()->create([
                            '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,
                            'local_name' => $item['local_name'],
                            'description' => $item['description'] ?? null,
                            'start_lat' => $item_start_coordinates[0],
                            'start_lon' => $item_start_coordinates[1],
                        ]);

                        $item_end_coordinates = null;
                        if ($item['instant_action'] == 0) {
                            if (!isset($item['priority'])) {
                                throw ValidationException::withMessages([
                                    "observed_items.$index.priority" => __('validation.required', ['attribute' => 'priority']),
                                ]);
                            }

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

                            $observed_item->priority = $item['priority'];
                            $observed_item->priority_fa = $item['priority_fa'];
                            $observed_item->save();
                        } elseif ($item['instant_action'] == 1) {
                            // $distance = 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']);

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

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

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

                                $before_image = $item['before_image'];
                                $after_image = $item['after_image'];
                            }

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

                            $start_time = Carbon::createFromFormat('Y-m-d H:i', $request->start_time);
                            $end_time = Carbon::createFromFormat('Y-m-d H:i', $request->end_time);
                            $activity_date = $start_time->average($end_time);

                            $attributes = [
                                'start_lat' => $item_start_coordinates[0],
                                'start_lng' => $item_start_coordinates[1],
                                'end_lat' => $item_end_coordinates ? $item_end_coordinates[0] : null,
                                'end_lng' => $item_end_coordinates ? $item_end_coordinates[1] : null,
                                // 'project_distance' => $distance,
                                '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' => $item['amount'],
                                'province_id' => auth()->user()->province_id,
                                'province_fa' => auth()->user()->province_fa,
                                'city_id' => auth()->user()->city_id,
                                'city_fa' => auth()->user()->city_fa,
                                'user_name' => auth()->user()->name,
                                'start_way_id' => $nominatimService->get_way_id_from_nominatim($item_start_coordinates[0], $item_start_coordinates[1]),
                                'end_way_id' => $item_end_coordinates ? $nominatimService->get_way_id_from_nominatim($item_end_coordinates[0], $item_end_coordinates[1]) : null,
                                'unit_fa' => $info_item->sub_item_unit,
                                'created_at_fa' => verta(Carbon::now())->format('Y-m-d H:i:s'),
                                'info_id' => $info_item->id,
                                'status' => 0,
                                'status_fa' => 'در حال بررسی',
                                'edarat_id' => auth()->user()->edarate_shahri_id,
                                'edarat_type' => EdarateShahri::class,
                                'edarat_name' => auth()->user()->edarate_shahri_name,
                                'activity_date' => $activity_date->format('Y-m-d'),
                                'activity_time' => $activity_date->format('H:i:s'),
                            ];

                            $road_item = RoadItemsProject::store(auth()->user(), $attributes, $before_image, $after_image, $observed_item->id);

                            if ($road_item === -1) {
                                return response()->json([
                                    'message' => 'اقدام مربوطه قبلا رسیدگی شده است.'
                                ], 400);
                            }
                        }
                    }
                }

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

                // Otp::useOtpToken($request->officer_phone_number, $request->verification_code);

                Sms::sendSms($request->officer_phone_number, "گشت راهداری با کد یکتای $road_patrol->id در تاریخ ".verta(\Carbon\Carbon::now())->format('Y-m-d H:i:s')." با شماره شما در سامانه RMS ثبت شد. \n لینک دریافت گزارش : \n https://rms.rmto.ir/v2/road_patrols/operator/report/$road_patrol->id");
                return $road_patrol;
            });
        } catch (\Throwable $th) {
            throw $th;
        }


        return response()->json([
            'road_patrol_id' => $road_patrol->id,
            'message' => 'succussful'
        ]);
    }

    public function getReport(Request $request, RoadPatrol $road_patrol)
    {
        // if (!auth()->user()->hasPermissionTo('add-road-patrol')) {
        //     abort(403);
        // }

        $data = [
            'serial_no' => $road_patrol->id,
            'province_fa' => $road_patrol->province_fa,
            'edare_name' => $road_patrol->edare_name,
            'start_time' => $road_patrol->start_time,
            'end_time' => $road_patrol->end_time,
            'officer_name' => $road_patrol->officer_name,
            'officer_plaque' => $road_patrol->officer_plaque,
            'officer_phone_number' => $road_patrol->officer_phone_number,
            'created_at' => $road_patrol->created_at
        ];

        $observed_items = array();
        if($road_patrol->observedItems) {
            foreach ($road_patrol->observedItems as $index => $observed_item) {
                $observed_items[] = [
                    'item' => $observed_item->item_name,
                    'sub_item' => $observed_item->sub_item_name,
                    'local_name' => $observed_item->local_name,
                    'description' => $observed_item->description,
                    'priority_fa' => $observed_item->priority_fa,
                ];
            }
        }

        $data['observed_items'] = $observed_items;
        return view('version2.dashboard_pages.road_patrols.report', ['data' => $data]);
    }

    public function getAllDataToMap(Request $request)
    {
        $date_from = $request->date_from ? $request->date_from .' 00:00:00' : Date('Y-m-d') .' 00:00:00';
        $date_to = $request->date_to ? $request->date_to.' 23:59:59' : (new \DateTime('tomorrow'))->format('Y-m-d').' 23:59:59';

        $data = RoadPatrol::when($request->province_id, function ($query, $province) {
            return $query->where('province_id', $province);
        })
                    ->when($request->edare_id, function ($query, $edare_id) {
                        return $query->where('edare_id', $edare_id);
                    })
                    ->whereBetween('created_at', [
                        $date_from,
                        $date_to,
                    ])
                    ->select('id', 'start_lat', 'start_lon')
                    ->get();

        return response()->json([
            'status' => 'succeed',
            'count' => count($data),
            'message' => '',
            'data' => $data
        ], 200);
    }

    public function map(Request  $request)
    {
        $province = $request->province_id;
        $edare_shahri = $request->edare_shahri_id;
        $status = $request->status;
        $rms_status = $request->rms_status;

        if ($request->date_from && $request->date_to) {
            $date_from = $request->date_from.' 00:00:00';
            $date_to = $request->date_to.' 23:59:59';
        } else {
            $date_from = Date('Y-m-d');
            $date_to = new \DateTime('tomorrow');
            $date_to = $date_to->format('Y-m-d');
        }

        $projects = RoadObserved::select('id', 'lng', 'lat','status')
            ->whereBetween('created_at', [$date_from, $date_to])
            ->when($province, function ($query) use ($province) {
                    return $query->where('province_id', $province);
            })
            ->when($rms_status, function ($query) use ($rms_status) {
                if ($rms_status == 2) {
                    return $query->where('rms_status', '<>',0);
                } else {
                    return $query->where('rms_status', 0);
                }
            })
            ->when($edare_shahri, function ($query) use ($edare_shahri) {
                return $query->where('edarate_shahri_id', $edare_shahri);
            })
            ->when($status, function ($query) use ($status) {
                return $query->where('status', $status);
            })
            // ->toSql();
            ->get();
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $projects
        ], 200);
    }

    public function detail(RoadPatrol $road_patrol)
    {
        return response()->json($road_patrol, 200);
    }

    public function operatorCartableReport(Request $request)
    {
        $name = 'گزارش از کارتابل عملیات گشت راهداری ' . verta()->now()->format('Y-m-d H:i') . '.xlsx';
        return Excel::download(new OperatorCartableExport($request->id, $request->status, $request->officer_name, $request->fromDate, $request->toDate), $name);
    }

    /**
     * Operator(End)
    */
}
