<?php

namespace App\Http\Controllers\V2\Dashboard;

use App\Http\Controllers\Controller;
use App\Services\NikarayanService;
use Illuminate\Http\Request;
use Hekmatinasser\Verta\Verta;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\RoadObservationHistory;
use Carbon\Carbon;
use SoapClient;
use App\Models\RoadObserved;
use App\Models\City;
use App\Models\User;
use App\Models\EdarateShahri;
use App\Models\Contractor;
use App\Facades\Sms\Sms;

use App\Exports\V2\RoadObservation\OperatorCartableExport;
use App\Exports\V2\RoadObservation\SupervisorCartableExport;
use App\Exports\V2\RoadObservation\PendingComplaintsExport;
use App\Exports\V2\RoadObservation\ReportComplaintsExport;
use Illuminate\Support\Str;

class RoadObservationController extends Controller
{
    /**
     * Supervisor(Begin)
     */
    public function supervisorCartable()
    {
        if (!auth()->user()->hasAnyPermission(['supervise-fast-react', 'supervise-fast-react-province'])) {
            abort(403);
        }
        auth()->user()->addActivityComplete(1137);

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

    public function supervisorShow(Request $request)
    {
        if (!auth()->user()->hasAnyPermission(['supervise-fast-react', 'supervise-fast-react-province'])) {
            abort(403);
        }

        // if($request->dev)
        //     dd($request->query());

        $fields = [
            'fk_RegisteredEventMessage',
            'road_observeds.id',
            'Title',
            'road_observeds.created_at',
            'lat',
            'lng',
            'FeatureTypeTitle',
            'Description',
            'MobileForSendEventSms',
            'rms_description',
            'rms_status',
            'rms_last_activity_fa',
            'rms_last_activity',
            'road_observeds.province_id',
            'province_fa',
            'city_fa',
            'edarate_shahri.name_fa',
            'status',
            'status_fa',
            'supervisor_description',
            'supervising_time'
        ];

        $aliases = ['', 'road_observeds_id', '', 'road_observeds_created_at', '', '', '', '', '', '', '', '', '', 'province_id', '', '', 'edarate_shahri_name_fa', '', '', '', ''];

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

        if (auth()->user()->hasPermissionTo('supervise-fast-react')) {

            $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
                //  ->where('rms_status', '!=', 0)
                ->whereNotNull('road_observeds.status')
                //  ->where(function ($query) {
                //      $query->where('status', 0)
                //          ->orWhere('supervisor_id', auth()->user()->id);
                //  })
                ->selectRaw($selectRaw)
                ->selectRaw("CONCAT('https://rms.rmto.ir/',image_before) as image_before, CONCAT('https://rms.rmto.ir/', image_after) as image_after");

        } elseif (auth()->user()->hasPermissionTo('supervise-fast-react-province')) {
            if (is_null(auth()->user()->province_id)) {
                return response()->json([
                    'message' => 'استانی برای شما در سامانه ثبت نشده است!'
                ], 400);
            }

            $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
                //  ->where('rms_status', '!=', 0)
                ->where('road_observeds.province_id', auth()->user()->province_id)
                ->whereNotNull('road_observeds.status')
                //  ->where(function ($query) {
                //      $query->where('status', 0)
                //          ->orWhere('supervisor_id', auth()->user()->id);
                //  })
                ->selectRaw($selectRaw)
                ->selectRaw("CONCAT('https://rms.rmto.ir/',image_before) as image_before, CONCAT('https://rms.rmto.ir/', image_after) as image_after");
        }

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

    public function verifyBySupervisor(Request $request, RoadObserved $roadObserved)
    {
        if (Gate::allows('gate-supervise-road-observed', $roadObserved)) {
            $request->validate([
                'verify' => 'required|in:1,2',
                'description' => 'nullable|string',
            ]);

            $status_fa = $request->verify == 1 ? 'تایید شده' : 'عدم تایید';
            $roadObserved->update([
                'status' => $request->verify,
                'status_fa' => $status_fa,
                'supervisor_id' => auth()->user()->id,
                'supervisor_name' => auth()->user()->name,
                'supervisor_description' => $request->description,
                'supervising_time' => now(),
            ]);
            auth()->user()->addActivityComplete(1138);

            return response()->json([
                'status' => 'succeed',
            ]);
        }

        return response()->json([
            'message' => 'access to requested resource is forbidden.'
        ], 403);
    }

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

    /**
     * Supervisor(End)
     */

    /**
     * Operator(Begin)
     */
    public function operatorCartable()
    {
        if (!auth()->user()->hasAnyPermission(['show-fast-react-edarate-shahri', 'show-fast-react-province', 'show-fast-react'])) {
            abort(403);
        }
        auth()->user()->addActivityComplete(1139);

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

    public function operatorShow(Request $request)
    {
        if (!auth()->user()->hasAnyPermission(['show-fast-react-edarate-shahri', 'show-fast-react-province', 'show-fast-react'])) {
            abort(403);
        }

        $fields = [
            'fk_RegisteredEventMessage',
            'road_observeds.id',
            'Title',
            'road_observeds.created_at',
            'lat',
            'lng',
            'FeatureTypeTitle',
            'Description',
            'MobileForSendEventSms',
            'rms_description',
            'rms_status',
            'rms_start_latlng',
            'rms_last_activity_fa',
            'rms_last_activity',
            'road_observeds.province_id',
            'province_fa',
            'city_fa',
            'edarate_shahri.name_fa',
            'status',
            'status_fa',
            'supervisor_description',
            'supervising_time'
        ];

        $aliases = ['', 'road_observeds_id', '', 'road_observeds_created_at', '', '', '', '', '', '', '', '', '', '', 'province_id', '', '', 'edarate_shahri_name_fa', '', '', '', ''];

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

        if (auth()->user()->hasPermissionTo('show-fast-react')) {
            $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
                ->where('rms_status', '!=', 0)
                ->whereNotNull('road_observeds.province_id')
                ->whereNotNull('status')
                ->selectRaw($selectRaw)
                ->selectRaw("CONCAT('https://rms.rmto.ir/',image_before) as image_before, CONCAT('https://rms.rmto.ir/', image_after) as image_after");
        } elseif (auth()->user()->hasPermissionTo('show-fast-react-province')) {
            if (is_null(auth()->user()->province_id)) {
                return response()->json([
                    'message' => 'استانی برای شما در سامانه ثبت نشده است!'
                ], 400);
            }

            $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
                ->where('rms_province_id', auth()->user()->province_id)
                ->where('rms_status', '!=', 0)
                ->whereNotNull('road_observeds.province_id')
                ->whereNotNull('status')
                ->selectRaw($selectRaw)
                ->selectRaw("CONCAT('https://rms.rmto.ir/',image_before) as image_before, CONCAT('https://rms.rmto.ir/', image_after) as image_after");
        } elseif (auth()->user()->hasPermissionTo('show-fast-react-edarate-shahri')) {
            if (is_null(auth()->user()->edarate_shahri_id)) {
                return response()->json([
                    'message' => 'اداره ای برای شما در سامانه ثبت نشده است!'
                ], 400);
            }

            $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
                ->where('edarate_shahri_id', auth()->user()->edarate_shahri_id)
                ->where('rms_status', '!=', 0)
                ->whereNotNull('road_observeds.province_id')
                ->whereNotNull('status')
                ->selectRaw($selectRaw)
                ->selectRaw("CONCAT('https://rms.rmto.ir/',image_before) as image_before, CONCAT('https://rms.rmto.ir/', image_after) as image_after");
        }

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

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

    public function pendingView()
    {
        if (!auth()->user()->hasAnyPermission(['show-fast-react-edarate-shahri', 'show-fast-react-province', 'show-fast-react'])) {
            abort(403);
        }
        auth()->user()->addActivityComplete(1140);

        return view('version2.dashboard_pages.fast_react.pending');
    }

    public function count()
    {
        if (!auth()->user()->permissions()->where('type', 'fastreact')->exists()) {
            abort(403);
        }

        $from_date_array = explode('-', verta()->startYear()->format('Y-m-d'));
        $from_datetime = implode('-', verta()->jalaliToGregorian($from_date_array[0], $from_date_array[1], $from_date_array[2])) . ' 00:00:00';
        $to_datetime = Carbon::now()->toDateString() . ' 23:59:59';

        if (auth()->user()->hasPermissionTo('show-fast-react')) {
            $data = RoadObserved::whereBetween('created_at', [$from_datetime, $to_datetime])
                ->selectRaw('sum(case when rms_status = 0 then 1 else 0 end) as pending,
                                             sum(case when rms_status != 0 then 1 else 0 end) as done')
                ->get();
        } elseif (auth()->user()->hasPermissionTo('show-fast-react-province')) {
            if (!auth()->user()->province_id) {
                return response()->json([
                    'message' => 'استانی برای شما در سامانه مشخص نشده است!'
                ], 400);
            }

            $data = RoadObserved::where('rms_province_id', Auth::user()->province_id)
                ->whereBetween('created_at', [$from_datetime, $to_datetime])
                ->selectRaw('sum(case when rms_status = 0 then 1 else 0 end) as pending,
                                         sum(case when rms_status != 0 then 1 else 0 end) as done')
                ->get();
        } elseif (auth()->user()->hasPermissionTo('show-fast-react-city')) {
            if (!auth()->user()->city_id) {
                return response()->json([
                    'message' => 'شهری برای شما در سامانه مشخص نشده است!'
                ], 400);
            }

            $data = RoadObserved::where('rms_city_id', Auth::user()->city_id)
                ->whereBetween('created_at', [$from_datetime, $to_datetime])
                ->selectRaw('sum(case when rms_status = 0 then 1 else 0 end) as pending,
                                         sum(case when rms_status != 0 then 1 else 0 end) as done')
                ->get();
        }

        return response()->json([
            'status' => 'succuss',
            'data' => $data
        ]);
    }

    public function showPending(Request $request)
    {
        if (!auth()->user()->hasAnyPermission(['show-fast-react-edarate-shahri', 'show-fast-react-province', 'show-fast-react'])) {
            abort(403);
        }

        if ($request->dev)
            dd(auth()->user()->permissions->pluck('name'));

        $fields = [
            'fk_RegisteredEventMessage',
            'road_observeds.id',
            'Title',
            'road_observeds.created_at',
            'road_observeds.StartTime_DateTime',
            'lat',
            'lng',
            'FeatureTypeTitle',
            'Description',
            'MobileForSendEventSms',
            'road_observeds.province_id',
            'province_fa',
            'city_fa',
            'edarate_shahri.name_fa'
        ];

        $aliases = ['', 'road_observeds_id', '', 'road_observeds_created_at', 'road_observeds_nikarayan_created_at', '', '', '', '', '', 'province_id', '', '', 'edarate_shahri_name_fa'];

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

        if (auth()->user()->hasPermissionTo('show-fast-react')) {
            $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
                ->where('rms_status', 0)
                ->whereNotNull('edarate_shahri_id')
                ->selectRaw($selectRaw);
        } elseif (auth()->user()->hasPermissionTo('show-fast-react-province')) {
            if (is_null(auth()->user()->province_id)) {
                return response()->json([
                    'message' => 'استانی برای شما در سامانه ثبت نشده است!'
                ], 400);
            }

            $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
                ->where('rms_status', 0)
                ->whereNotNull('edarate_shahri_id')
                ->where('road_observeds.province_id', auth()->user()->province_id)
                ->selectRaw($selectRaw);

            // dd(2);
        } elseif (auth()->user()->hasPermissionTo('show-fast-react-edarate-shahri')) {
            if (is_null(auth()->user()->edarate_shahri_id)) {
                return response()->json([
                    'message' => 'اداره ای برای شما در سامانه ثبت نشده است!'
                ], 400);
            }

            $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
                ->where('rms_status', 0)
                ->whereNotNull('edarate_shahri_id')
                ->where('edarate_shahri_id', auth()->user()->edarate_shahri_id)
                ->selectRaw($selectRaw);

        }

        $data = processDataTable($request, '', $fields, $query);

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



    public function referList(int $id)
    {
        $edarat_shahri = EdarateShahri::where('province_id', $id)->select('id', 'name_fa', 'province_id')->get();
        // $contractors = Contractor::where('province_id', $id)->select('id', 'name', 'province_id')->get();

        return response()->json([
            'status' => 200,
            'data' => $edarat_shahri,
        ]);
    }
    public function referReport(Request $request, RoadObserved $roadObserved)
    {
        $data = RoadObservationHistory::where('road_observation_histories.id', $roadObserved->id)->where('action', 'refer')->get();
        foreach ($data as $key => $value) {
            $data[$key]->from_edareh = EdarateShahri::find($value->from_edareh)->name_fa;
            $data[$key]->to_edareh = EdarateShahri::find($value->to_edareh)->name_fa;
            $user = User::find($value->user_id);
            $data[$key]->user = $user->first_name . ' ' . $user->last_name;
        }
        return response()->json([
            'status' => 200,
            'data' => $data,
        ]);
    }

    public function refer(Request $request, RoadObserved $roadObserved)
    {
        $request->validate([
            'edarate_shahri_id' => 'required|numeric',
            'refer_description' => 'required|string',
        ]);

        if ($roadObserved->rms_status != 0) {
            return response()->json([
                'message' => 'access to requested resource is forbidden.'
            ], 403);
        }
        $from_edareh = $roadObserved->edarate_shahri_id;
        $roadObserved->update([
            'edarate_shahri_id' => $request->edarate_shahri_id,
        ]);

        RoadObservationHistory::create([
            'id' => $roadObserved->id,
            'user_id' => auth()->user()->id,
            'action' => 'refer',
            'description' => $request->refer_description,
            'from_edareh' => $from_edareh,
            'to_edareh' => $request->edarate_shahri_id
        ]);

        auth()->user()->addActivityComplete(1037);
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $roadObserved
        ], 200);
    }

    public function restore(Request $request, RoadObserved $roadObserved)
    {
        if (!auth()->user()->hasPermissionTo('restore-fast-react')) {
            abort(403);
        }

        $request->validate([
            'restore_description' => 'required|string',
        ]);

        if ($roadObserved->image_before) {
            $before_path = explode('/', $roadObserved->image_before);
            Storage::delete('public/' . implode('/', array_slice($before_path, 1)));
        }

        if ($roadObserved->image_after) {
            $after_path = explode('/', $roadObserved->image_after);
            Storage::delete('public/' . implode('/', array_slice($after_path, 1)));
        }

        $roadObserved->update([
            'image_before' => null,
            'image_after' => null,
            'rms_last_activity' => null,
            'rms_last_activity_fa' => null,
            'updated_at_fa' => null,
            'updated_at' => null,
            'rms_status' => 0,
            'status' => null,
            'status_fa' => null,
        ]);

        RoadObservationHistory::create([
            'id' => $roadObserved->id,
            'user_id' => auth()->user()->id,
            'action' => 'restore',
            'description' => $request->restore_description,
        ]);

        auth()->user()->addActivityComplete(1141);
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $roadObserved
        ], 200);
    }

    public function handle(Request $request, RoadObserved $roadObserved, NikarayanService $nikarayanService)
    {
        if (!auth()->user()->hasAnyPermission(['show-fast-react-edarate-shahri', 'show-fast-react-province', 'show-fast-react'])) {
            return response()->json([
                'message' => 'access to requested resource is forbidden.'
            ], 403);
        }

        $files_path = [];
        $file_index = 0;
        $file_time = time();
        // $uuid = \Uuid::generate();
        $uuid = (string) Str::uuid();

        if ($request->file('image-before-1')) {
            $roadObserved->files()->where('path', 'like', '%_image-before-1_%')->delete();

            $files_path[$file_index]['path'] = $request->file('image-before-1')->storeAs(
                'public/road_observeds',
                'img4_' . $file_time . '_image-before-1_' . $roadObserved->id . '_' . $uuid . '.' . $request->file('image-before-1')->extension()
            );
            $file_index++;
            $roadObserved->image_before = 'storage/road_observeds/' . 'img4_' . $file_time . '_image-before-1_' . $roadObserved->id . '_' . $uuid . '.' . $request->file('image-before-1')->extension();
        }

        if ($request->file('image-after-1')) {
            $roadObserved->files()->where('path', 'like', '%_image-after-1_%')->delete();

            $files_path[$file_index]['path'] = $request->file('image-after-1')->storeAs(
                'public/road_observeds',
                'img4_' . $file_time . '_image-after-1_' . $roadObserved->id . '_' . $uuid . '.' . $request->file('image-after-1')->extension()
            );
            $file_index++;
            $roadObserved->image_after = 'storage/road_observeds/' . 'img4_' . $file_time . '_image-after-1_' . $roadObserved->id . '_' . $uuid . '.' . $request->file('image-after-1')->extension();
        }

        ///////  milad i uncomment this
        $files = json_encode($files_path);
        $roadObserved->problemHistories()->create([
            'user_id' => Auth::user()->id, //$request->user()->id,// 470
            'previous_rms_status' => $roadObserved->rms_status,
            'previous_rms_start_latlng' => $roadObserved->rms_start_latlng,
            'previous_rms_end_latlng' => $roadObserved->rms_end_latlng,
            'previous_rms_description' => $roadObserved->rms_description,
            'new_files' => $files
        ]);

        $roadObserved->rms_status = $request->input('rms-status') ?? $roadObserved->rms_status;
        if ($request->input('start_point')) {
            $roadObserved->rms_start_latlng = explode(',', $request->input('start_point')) ?? null;
        }
        // if ($request->input('rms-end-latlng')) {
        //     $roadObserved->rms_end_latlng = explode(',', $request->input('rms-end-latlng')) ?? null;
        // }
        $roadObserved->rms_description = $request->input('description') ?? $roadObserved->rms_description;

        $now_date_time = Carbon::now();
        $roadObserved->updated_at_fa = Verta::instance($now_date_time);

        $roadObserved->rms_last_activity_fa = Verta::instance($now_date_time);
        $roadObserved->rms_last_activity = $now_date_time;

        /**
         * Hamid edit
         */
        $roadObserved->status = 0;
        $roadObserved->status_fa = 'در حال بررسی';
        $roadObserved->save();
        auth()->user()->addActivityComplete(1142);

        // if ($file_index > 0) {
        //     $roadObserved->files()->createMany($files_path);
        // }
//        $url = "https://riws.rmto.ir/WebServices/NRPTrafficStatus.asmx?wsdl";
        try {
            $result = $nikarayanService->updateRoadObservedInfoByNikarayan($request, $roadObserved, $files_path);
        } catch (SoapFault $e) {

            $msg = "error in send to nikarayan at" . date("Y-m-d H:i:s") . "\n" . 'rms: error in get road observation webservice babe!!!!' . "\n";
            $msg .= $e->getMessage();

            Sms::sendSms(env('RMS_CTO_PHONE_NUMBER'), $msg);
        }
        ///// sms send

        return response()->json([
            'status' => 'succeed',
            'message' => 1,
            'data' => $roadObserved,
            'nikarayan_res' => $result
        ], 201);
    }

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

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

    public function roadObserveDetail(RoadObserved $roadObserved)
    {
        return response()->json([
            'status' => 'succeed',
            'message' => 1,
            'data' => $roadObserved->load("edarateShahri"),
        ], 200);
    }
}
