<?php

namespace App\Http\Controllers;

use App\Models\DangerPoint;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Hekmatinasser\Verta\Verta;
use Illuminate\Support\Facades\DB;
use App\Models\DangerPointAccident;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Barryvdh\Snappy\Facades\SnappyPdf;

class DangerPointController extends Controller
{
    public function getUserProvince(Request $request)
    {
        if ($request->user()->province_id != null
           && ($request->user()->username == 'witeL' || $request->user()->username == 'drdanesh')) {
            $provinces = \App\Models\Province::all();
        } else {
            $provinces = \App\Models\Province::find($request->user()->province_id);
        }

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

    public function getDangerPoint()
    {
        if (Auth::user()->province_id != null
            && (Auth::user()->username == 'witel' || Auth::user()->username == 'drdanesh')) {
            $dangerPoints = DangerPoint::all();
            // $dangerPoints = DangerPoint::limit(10)->get();
        } else {
            $dangerPoints = DangerPoint::where('province_id', Auth::user()->province_id)
                ->get();
        }

        $dangerPointsArray = [];

        foreach ($dangerPoints as $key => $dangerPoint) {
            $dangerPointsArray[$key] = [
                'id' => $dangerPoint->id,
                'province' => [
                    'id' => $dangerPoint->province->id,
                    'name' => $dangerPoint->province->name_fa
                ],
                'axis_name' => $dangerPoint->axis_name,
                'axis_type' => $dangerPoint->axis_type,
                'axis_start' => $dangerPoint->axis_start,
                'axis_end' => $dangerPoint->axis_end,
                'distance_axis_start' => $dangerPoint->distance_axis_start,
                'local_name' => $dangerPoint->local_name,
                'lat_lng' => [
                    $dangerPoint->lat,
                    $dangerPoint->lng
                ],
                'accident_251' => $dangerPoint->accident_251,
                'accident_251_code' => $dangerPoint->accident_251_code,
                'speed_limit' => $dangerPoint->speed_limit,
                'speed_average' => $dangerPoint->speed_average,
                'accident_possibility' => $dangerPoint->accident_possibility,
                'road_guard' => $dangerPoint->road_guard,
                'geometric_desc' => $dangerPoint->geometric_desc,
                'accident_cause' => $dangerPoint->accident_cause,
                'accident_cause_suggest' => $dangerPoint->accident_cause_suggest,
                'accident_severity' => $dangerPoint->accident_severity,
                'accident_severity_suggest' => $dangerPoint->accident_severity_suggest,
                'correction_plan_done' => $dangerPoint->correction_plan_done,
                'correction_plan_doing' => $dangerPoint->correction_plan_doing,
                'correction_plan_doing_desc' => $dangerPoint->correction_plan_doing_desc,
                'correction_plan_doing_suggest' => $dangerPoint->correction_plan_doing_suggest,
                'point_images' => $dangerPoint->files,
                'btn_deactive' => [
                    (($dangerPoint->dangerPointAccidents()->count() > 0) ? 0 : 1),
                    (($dangerPoint->speed_limit != null) ? 0 : 1),
                    1,
                    (($dangerPoint->files()->count() == 9) ? 0 : 1),
                    (($dangerPoint->signature_file != null && $dangerPoint->police_file != null) ? 0 : 1),
                    1
                ],
                'uploaded_files' => [
                    ['signature_file' => ($dangerPoint->signature_file) ? asset('storage' . substr($dangerPoint->signature_file, 6)) : null],
                    ['police_file' => ($dangerPoint->police_file) ? asset('storage' . substr($dangerPoint->police_file, 6)) : null]
                ],
                'status' => $dangerPoint->status,
                'status_desc' => $dangerPoint->status_desc,
                'submited_at' => verta($dangerPoint->created_at)->format('Y/m/d'),
                'code' => $dangerPoint->code
            ];

            if ($dangerPointsArray[$key]['btn_deactive'][0] == 0 && $dangerPointsArray[$key]['btn_deactive'][1] == 0) {
                $dangerPointsArray[$key]['btn_deactive'][2] = 0;
            }

            if ($dangerPointsArray[$key]['btn_deactive'][0] == 0
             && $dangerPointsArray[$key]['btn_deactive'][1] == 0
             && $dangerPointsArray[$key]['btn_deactive'][2] == 0
             && $dangerPointsArray[$key]['btn_deactive'][3] == 0
             && $dangerPointsArray[$key]['btn_deactive'][4] == 0) {
                $dangerPointsArray[$key]['btn_deactive'][5] = 0;
            }
        }

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $dangerPointsArray,
            // 'can_submit' => (((Auth::user()->hasRole('imenivaharim')) || Auth::user()->hasRole('witel') || Auth::user()->hasRole('admin')) ? 1 : 0)
            'can_submit' => 1
        ], 200);
    }

    public function getDangerPointAdmin()
    {
        $dangerPoints = DangerPoint::whereIn('status', [1, 2, 3])->get();

        $dangerPointsArray = [];

        foreach ($dangerPoints as $key => $dangerPoint) {
            $dangerPointsArray[$key] = [
                'id' => $dangerPoint->id,
                'province' => [
                    'id' => $dangerPoint->province->id,
                    'name' => $dangerPoint->province->name_fa
                ],
                'axis_name' => $dangerPoint->axis_name,
                'axis_type' => $dangerPoint->axis_type,
                'axis_start' => $dangerPoint->axis_start,
                'axis_end' => $dangerPoint->axis_end,
                'distance_axis_start' => $dangerPoint->distance_axis_start,
                'local_name' => $dangerPoint->local_name,
                'lat_lng' => [
                    $dangerPoint->lat,
                    $dangerPoint->lng
                ],
                'accident_251' => $dangerPoint->accident_251,
                'accident_251_code' => $dangerPoint->accident_251_code,
                'speed_limit' => $dangerPoint->speed_limit,
                'speed_average' => $dangerPoint->speed_average,
                'accident_possibility' => $dangerPoint->accident_possibility,
                'road_guard' => $dangerPoint->road_guard,
                'geometric_desc' => $dangerPoint->geometric_desc,
                'accident_cause' => $dangerPoint->accident_cause,
                'accident_cause_suggest' => $dangerPoint->accident_cause_suggest,
                'accident_severity' => $dangerPoint->accident_severity,
                'accident_severity_suggest' => $dangerPoint->accident_severity_suggest,
                'correction_plan_done' => $dangerPoint->correction_plan_done,
                'correction_plan_doing' => $dangerPoint->correction_plan_doing,
                'correction_plan_doing_desc' => $dangerPoint->correction_plan_doing_desc,
                'correction_plan_doing_suggest' => $dangerPoint->correction_plan_doing_suggest,
                'point_images' => $dangerPoint->files,
                'btn_deactive' => [
                    0,
                    0,
                    0,
                    0
                ],
                'uploaded_files' => [
                    ['signature_file' => ($dangerPoint->signature_file) ? asset('storage' . substr($dangerPoint->signature_file, 6)) : null],
                    ['police_file' => ($dangerPoint->police_file) ? asset('storage' . substr($dangerPoint->police_file, 6)) : null]
                ],
                'status' => $dangerPoint->status,
                'status_desc' => $dangerPoint->status_desc,
                'submited_at' => verta($dangerPoint->created_at)->format('Y/m/d'),
                'code' => $dangerPoint->code
            ];
        }

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

    public function getDangerAccidents($id)
    {
        $dangerAccidents = DangerPoint::find($id)->dangerPointAccidents;

        $dangerAccidentsArray = [];

        foreach ($dangerAccidents as $key => $dangerAccident) {
            $dangerAccidentsArray[$key] = [
                'id' => $dangerAccident->id,
                'serial_number' => $dangerAccident->serial_number,
                'accident_date' => (($dangerAccident->accident_date) ? verta($dangerAccident->accident_date)->format('Y/m/d') : $dangerAccident->accident_date),
                'day' => $dangerAccident->day,
                'time' => $dangerAccident->time,
                'accident_direction' => $dangerAccident->accident_direction,
                'collision_type' => $dangerAccident->collision_type,
                'accident_factors' => $dangerAccident->accident_factors,
                'accident_type' => $dangerAccident->accident_type ?? [],
                'accident_result' => $dangerAccident->accident_result
            ];
        }

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

    public function storeDanger(Request $request)
    {
        $request->validate([
            'province-id' => 'required|integer|exists:provinces,id',
            'axis-name' => 'required|string',
            'axis-type' => 'required|integer|between:1,6',
            'axis-start' => 'required|string',
            'axis-end' => 'required|string',
            'distance-axis-start' => 'required|numeric',
            'local-name' => 'required|string',
            'lat' => 'required|string|regex:/^[1-9][0-9]\.[0-9]{1,}$/i',
            'lng' => 'required|string|regex:/^[1-9][0-9]\.[0-9]{1,}$/i'
        ]);

        $dangerPoint = new DangerPoint;

        // PUBLIC URL
        //$dangerPoint->user_id = 470;
        $dangerPoint->user_id = $request->user()->id;
        $dangerPoint->province_id = $request->input('province-id') ?? null;
        $dangerPoint->axis_name = $request->input('axis-name') ?? null;
        $dangerPoint->axis_type = $request->input('axis-type') ?? null;
        $dangerPoint->axis_start = $request->input('axis-start') ?? null;
        $dangerPoint->axis_end = $request->input('axis-end') ?? null;
        $dangerPoint->distance_axis_start = $request->input('distance-axis-start') ?? null;
        $dangerPoint->local_name = $request->input('local-name') ?? null;
        $dangerPoint->lat = $request->input('lat') ?? null;
        $dangerPoint->lng = $request->input('lng') ?? null;

        $dangerPoint->save();

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

    public function storeDangerDetails(Request $request)
    {
        $request->validate([
            'danger-id' => 'required|integer|exists:danger_points,id',
            'accident-251' => 'required|boolean',
            'accident-251-code' => 'required_if:accident-251,1|string',
            'speed-limit' => 'required|integer',
            'speed-average' => 'required|integer',
            'accident-possibility' => 'required|boolean',
            'road-guard' => 'required|boolean',
            'geometric-desc' => 'required|integer|between:1,16',
            'accident-cause' => 'string',
            'accident-cause-suggest' => 'string',
            // 'accident-severity' => 'string',
            // 'accident-severity-suggest' => 'string',
            'correction-plan-done' => 'string',
            'correction-plan-doing' => 'string',
            'correction-plan-doing-desc' => 'string',
            'correction-plan-doing-suggest' => 'string',
            //'signature-file' => 'required|file'
        ]);

        $dangerPoint = DangerPoint::find($request->input('danger-id'));

        $dangerPoint->accident_251 = $request->input('accident-251') ?? null;
        $dangerPoint->accident_251_code = $request->input('accident-251-code') ?? null;
        $dangerPoint->speed_limit = $request->input('speed-limit') ?? null;
        $dangerPoint->speed_average = $request->input('speed-average') ?? null;
        $dangerPoint->accident_possibility = $request->input('accident-possibility') ?? null;
        $dangerPoint->road_guard = $request->input('road-guard') ?? null;
        $dangerPoint->geometric_desc = $request->input('geometric-desc') ?? null;
        if ($request->input('accident-cause')) {
            $dangerPoint->accident_cause = explode(',', $request->input('accident-cause')) ?? null;
        } else {
            $dangerPoint->accident_cause = null;
        }
        $dangerPoint->accident_cause_suggest = $request->input('accident-cause-suggest') ?? null;
        if ($request->input('accident-severity')) {
            $dangerPoint->accident_severity = explode(',', $request->input('accident-severity')) ?? null;
        } else {
            $dangerPoint->accident_severity = null;
        }
        $dangerPoint->accident_severity_suggest = $request->input('accident-severity-suggest') ?? null;
        $dangerPoint->correction_plan_done = $request->input('correction-plan-done') ?? null;
        $dangerPoint->correction_plan_doing = $request->input('correction-plan-doing') ?? null;
        $dangerPoint->correction_plan_doing_desc = $request->input('correction-plan-doing-desc') ?? null;
        $dangerPoint->correction_plan_doing_suggest = $request->input('correction-plan-doing-suggest') ?? null;

        // $files_path = null;

        // if ($request->file('signature-file')) {
        //     $files_path = $request->file('signature-file')->storeAs(
        //         'public/danger-points/signature',
        //         'sign_' . time() . '_signature_file_' . $dangerPoint->id . '_' . $request->file('signature-file')->getClientOriginalName()
        //     );
        // }

        // $dangerPoint->signature_file = $files_path;

        $dangerPoint->save();

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

    public function storeDangerAccident(Request $request)
    {
        $request->validate([
            'danger-id' => 'required|integer|exists:danger_points,id',
            'serial-number' => 'required|string',
            'accident-date' => 'required|string',
            'day' => 'required|integer|between:1,7',
            'time' => 'required|string',
            'accident-direction' => 'required|integer|between:1,2',
            'collision-type' => 'required|integer|between:1,6',
            'accident-factors' => 'required|json',
            'accident-type' => 'required|integer|between:1,3',
            'accident-result' => 'required|json'
        ]);

        $dangerPoint = DangerPoint::find($request->input('danger-id'));

        $accDate = explode('-', $request->input('accident-date'));
        $accDateGregorian = Verta::getGregorian($accDate[0], $accDate[1], $accDate[2]);
        if (count($accDateGregorian) == 3) {
            $accDateGregorianSt = $accDateGregorian[0] . '-' . $accDateGregorian[1] . '-' .$accDateGregorian[2];
        } else {
            $accDateGregorianSt = null;
        }

        $dangerPointAccident = $dangerPoint->dangerPointAccidents()->create([
            // PUBLIC URL
            'user_id' => $request->user()->id,
            'serial_number' => $request->input('serial-number') ?? null,
            'accident_date' => $accDateGregorianSt,
            'day' => $request->input('day') ?? null,
            'time' => $request->input('time') ?? null,
            'accident_direction' => $request->input('accident-direction') ?? null,
            'collision_type' => $request->input('collision-type') ?? null,
            'accident_factors' => (($request->input('accident-factors')) ? json_decode($request->input('accident-factors')) : null),
            'accident_type' => $request->input('accident-type') ?? null,
            'accident_result' => (($request->input('accident-result')) ? json_decode($request->input('accident-result')) : null)
        ]);

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $dangerPointAccident
        ], 201);
    }
    
    public function storeDangerImages(Request $request)
    {
        $request->validate([
            'danger-id' => 'required|integer|exists:danger_points,id',
            'image-right-100-1' => 'image',
            'image-right-100-2' => 'image',
            'image-right-50-1' => 'image',
            'image-right-50-2' => 'image',
            'image-left-100-1' => 'image',
            'image-left-100-2' => 'image',
            'image-left-50-1' => 'image',
            'image-left-50-2' => 'image',
            'image-satellite' => 'image'
        ]);

        $dangerPoint = DangerPoint::find($request->input('danger-id'));

        $files_path = [];
        $file_index = 0;
        $file_time = time();

        if ($request->file('image-right-100-1')) {
            $dangerPoint->files()->where('path', 'like', '%_image-right-100-1_0_%')->delete();

            $files_path[$file_index]['path'] = $request->file('image-right-100-1')->storeAs(
                'public/danger_points',
                'img9_' . $file_time . '_image-right-100-1_0_' . $dangerPoint->id . '_' . $request->file('image-right-100-1')->getClientOriginalName()
            );
            $file_index++;
        }
        if ($request->file('image-right-100-2')) {
            $dangerPoint->files()->where('path', 'like', '%_image-right-100-2_1_%')->delete();
            
            $files_path[$file_index]['path'] = $request->file('image-right-100-2')->storeAs(
                'public/danger_points',
                'img9_' . $file_time . '_image-right-100-2_1_' . $dangerPoint->id . '_' . $request->file('image-right-100-2')->getClientOriginalName()
            );
            $file_index++;
        }
        if ($request->file('image-right-50-1')) {
            $dangerPoint->files()->where('path', 'like', '%_image-right-50-1_2_%')->delete();
            
            $files_path[$file_index]['path'] = $request->file('image-right-50-1')->storeAs(
                'public/danger_points',
                'img9_' . $file_time . '_image-right-50-1_2_' . $dangerPoint->id . '_' . $request->file('image-right-50-1')->getClientOriginalName()
            );
            $file_index++;
        }
        if ($request->file('image-right-50-2')) {
            $dangerPoint->files()->where('path', 'like', '%_image-right-50-2_3_%')->delete();
            
            $files_path[$file_index]['path'] = $request->file('image-right-50-2')->storeAs(
                'public/danger_points',
                'img9_' . $file_time . '_image-right-50-2_3_' . $dangerPoint->id . '_' . $request->file('image-right-50-2')->getClientOriginalName()
            );
            $file_index++;
        }
        if ($request->file('image-left-100-1')) {
            $dangerPoint->files()->where('path', 'like', '%_image-left-100-1_4_%')->delete();

            $files_path[$file_index]['path'] = $request->file('image-left-100-1')->storeAs(
                'public/danger_points',
                'img9_' . $file_time . '_image-left-100-1_4_' . $dangerPoint->id . '_' . $request->file('image-left-100-1')->getClientOriginalName()
            );
            $file_index++;
        }
        if ($request->file('image-left-100-2')) {
            $dangerPoint->files()->where('path', 'like', '%_image-left-100-2_5_%')->delete();
            
            $files_path[$file_index]['path'] = $request->file('image-left-100-2')->storeAs(
                'public/danger_points',
                'img9_' . $file_time . '_image-left-100-2_5_' . $dangerPoint->id . '_' . $request->file('image-left-100-2')->getClientOriginalName()
            );
            $file_index++;
        }
        if ($request->file('image-left-50-1')) {
            $dangerPoint->files()->where('path', 'like', '%_image-left-50-1_6_%')->delete();
            
            $files_path[$file_index]['path'] = $request->file('image-left-50-1')->storeAs(
                'public/danger_points',
                'img9_' . $file_time . '_image-left-50-1_6_' . $dangerPoint->id . '_' . $request->file('image-left-50-1')->getClientOriginalName()
            );
            $file_index++;
        }
        if ($request->file('image-left-50-2')) {
            $dangerPoint->files()->where('path', 'like', '%_image-left-50-2_7_%')->delete();
            
            $files_path[$file_index]['path'] = $request->file('image-left-50-2')->storeAs(
                'public/danger_points',
                'img9_' . $file_time . '_image-left-50-2_7_' . $dangerPoint->id . '_' . $request->file('image-left-50-2')->getClientOriginalName()
            );
            $file_index++;
        }
        if ($request->file('image-satellite')) {
            $dangerPoint->files()->where('path', 'like', '%_image-satellite_8_%')->delete();
            
            $files_path[$file_index]['path'] = $request->file('image-satellite')->storeAs(
                'public/danger_points',
                'img9_' . $file_time . '_image-satellite_8_' . $dangerPoint->id . '_' . $request->file('image-satellite')->getClientOriginalName()
            );
            $file_index++;
        }

        $dangerPoint->files()->createMany($files_path);

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $dangerPoint->files
        ], 201);
    }

    public function storeDangerPreviewImage(Request $request)
    {
        $request->validate([
            'danger-id' => 'required|integer|exists:danger_points,id',
            'image' => 'required|image',
            'name' => 'required|string'
        ]);

        $dangerPoint = DangerPoint::find($request->input('danger-id'));

        $dangerPoint->files()->where('path', 'like', '%img9_' . $request->input('name') . '_%')->delete();

        $files_path = $request->file('image')->storeAs(
            'public/danger_points',
            'img9_' . $request->input('name') . '_' . $dangerPoint->id . '_' . time() . '_' . $request->file('image')->getClientOriginalName()
        );

        $dangerPoint->files()->create([
            'path' => $files_path
        ]);

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

    public function destroyDangerPreviewImage(Request $request)
    {
        $request->validate([
            'danger-id' => 'required|integer|exists:danger_points,id',
            'name' => 'required|string'
        ]);

        $dangerPoint = DangerPoint::find($request->input('danger-id'));

        $dangerPoint->files()->where('path', 'like', '%_' . $request->input('name') . '_%')->delete();

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

    public function showDangerPointPage()
    {
        return view('rmto-preview.pages.danger-point');
    }

    public function showDangerPointAdminPage()
    {
        return view('rmto-preview.pages.danger-point-admin');
        // if (Auth::user()->username == 'witeL' || Auth::user()->username == 'drdanesh') {
        // } else {
        //     return redirect('/danger-point');
        // }
    }

    public function updateDanger(Request $request, $id)
    {
        $request->validate([
            'province-id' => 'required|integer|exists:provinces,id',
            'axis-name' => 'required|string',
            'axis-type' => 'required|integer|between:1,6',
            'axis-start' => 'required|string',
            'axis-end' => 'required|string',
            'distance-axis-start' => 'required|numeric',
            'local-name' => 'required|string',
            'lat' => 'required|string|regex:/^[1-9][0-9]\.[0-9]{1,}$/i',
            'lng' => 'required|string|regex:/^[1-9][0-9]\.[0-9]{1,}$/i'
        ]);

        $dangerPoint = DangerPoint::find($id);

        $dangerPoint->dangerPointHistories()->create([
            // PUBLIC URL
            'user_id' => $request->user()->id,
            'previous_code' => $dangerPoint->code,
            'previous_axis_name' => $dangerPoint->axis_name,
            'previous_axis_type' => $dangerPoint->axis_type,
            'previous_axis_start' => $dangerPoint->axis_start,
            'previous_axis_end' => $dangerPoint->axis_end,
            'previous_distance_axis_start' => $dangerPoint->distance_axis_start,
            'previous_local_name' => $dangerPoint->local_name,
            'previous_lat' => $dangerPoint->lat,
            'previous_lng' => $dangerPoint->lng,
            'previous_accident_251' => $dangerPoint->accident_251,
            'previous_accident_251_code' => $dangerPoint->accident_251_code,
            'previous_speed_limit' => $dangerPoint->speed_limit,
            'previous_speed_average' => $dangerPoint->speed_average,
            'previous_accident_possibility' => $dangerPoint->accident_possibility,
            'previous_road_guard' => $dangerPoint->road_guard,
            'previous_geometric_desc' => $dangerPoint->geometric_desc,
            'previous_accident_cause' => $dangerPoint->accident_cause,
            'previous_accident_cause_suggest' => $dangerPoint->accident_cause_suggest,
            'previous_accident_severity' => $dangerPoint->accident_severity,
            'previous_accident_severity_suggest' => $dangerPoint->accident_severity_suggest,
            'previous_correction_plan_done' => $dangerPoint->correction_plan_done,
            'previous_correction_plan_doing' => $dangerPoint->correction_plan_doing,
            'previous_correction_plan_doing_desc' => $dangerPoint->correction_plan_doing_desc,
            'previous_correction_plan_doing_suggest' => $dangerPoint->correction_plan_doing_suggest,
            'previous_status' => $dangerPoint->status,
            'previous_status_desc' => $dangerPoint->status_desc
        ]);

        $dangerPoint->province_id = $request->input('province-id') ?? $dangerPoint->province_id;
        $dangerPoint->axis_name = $request->input('axis-name') ?? $dangerPoint->axis_name;
        $dangerPoint->axis_type = $request->input('axis-type') ?? $dangerPoint->axis_type;
        $dangerPoint->axis_start = $request->input('axis-start') ?? $dangerPoint->axis_start;
        $dangerPoint->axis_end = $request->input('axis-end') ?? $dangerPoint->axis_end;
        $dangerPoint->distance_axis_start = $request->input('distance-axis-start') ?? $dangerPoint->distance_axis_start;
        $dangerPoint->local_name = $request->input('local-name') ?? $dangerPoint->local_name;
        $dangerPoint->lat = $request->input('lat') ?? $dangerPoint->lat;
        $dangerPoint->lng = $request->input('lng') ?? $dangerPoint->lng;

        $dangerPoint->save();

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

    public function updateDangerDetails(Request $request, $id)
    {
        $request->validate([
            'accident-251' => 'required|boolean',
            'accident-251-code' => 'required_if:accident-251,1|string',
            'speed-limit' => 'required|integer',
            'speed-average' => 'required|integer',
            'accident-possibility' => 'required|boolean',
            'road-guard' => 'required|boolean',
            'geometric-desc' => 'required|integer|between:1,16',
            'accident-cause' => 'string',
            'accident-cause-suggest' => 'string',
            // 'accident-severity' => 'string',
            // 'accident-severity-suggest' => 'string',
            'correction-plan-done' => 'string',
            'correction-plan-doing' => 'string',
            'correction-plan-doing-desc' => 'string',
            'correction-plan-doing-suggest' => 'string',
            //'signature-file' => 'required|file'
        ]);

        $dangerPoint = DangerPoint::find($id);

        $dangerPoint->dangerPointHistories()->create([
            // PUBLIC URL
            'user_id' => $request->user()->id,
            'previous_code' => $dangerPoint->code,
            'previous_axis_name' => $dangerPoint->axis_name,
            'previous_axis_type' => $dangerPoint->axis_type,
            'previous_axis_start' => $dangerPoint->axis_start,
            'previous_axis_end' => $dangerPoint->axis_end,
            'previous_distance_axis_start' => $dangerPoint->distance_axis_start,
            'previous_local_name' => $dangerPoint->local_name,
            'previous_lat' => $dangerPoint->lat,
            'previous_lng' => $dangerPoint->lng,
            'previous_accident_251' => $dangerPoint->accident_251,
            'previous_accident_251_code' => $dangerPoint->accident_251_code,
            'previous_speed_limit' => $dangerPoint->speed_limit,
            'previous_speed_average' => $dangerPoint->speed_average,
            'previous_accident_possibility' => $dangerPoint->accident_possibility,
            'previous_road_guard' => $dangerPoint->road_guard,
            'previous_geometric_desc' => $dangerPoint->geometric_desc,
            'previous_accident_cause' => $dangerPoint->accident_cause,
            'previous_accident_cause_suggest' => $dangerPoint->accident_cause_suggest,
            'previous_accident_severity' => $dangerPoint->accident_severity,
            'previous_accident_severity_suggest' => $dangerPoint->accident_severity_suggest,
            'previous_correction_plan_done' => $dangerPoint->correction_plan_done,
            'previous_correction_plan_doing' => $dangerPoint->correction_plan_doing,
            'previous_correction_plan_doing_desc' => $dangerPoint->correction_plan_doing_desc,
            'previous_correction_plan_doing_suggest' => $dangerPoint->correction_plan_doing_suggest,
            'previous_status' => $dangerPoint->status,
            'previous_status_desc' => $dangerPoint->status_desc
        ]);

        $dangerPoint->accident_251 = $request->input('accident-251') ?? $dangerPoint->accident_251;
        $dangerPoint->accident_251_code = $request->input('accident-251-code') ?? $dangerPoint->accident_251_code;
        $dangerPoint->speed_limit = $request->input('speed-limit') ?? $dangerPoint->speed_limit;
        $dangerPoint->speed_average = $request->input('speed-average') ?? $dangerPoint->speed_average;
        $dangerPoint->accident_possibility = $request->input('accident-possibility') ?? $dangerPoint->accident_possibility;
        $dangerPoint->road_guard = $request->input('road-guard') ?? $dangerPoint->road_guard;
        $dangerPoint->geometric_desc = $request->input('geometric-desc') ?? $dangerPoint->geometric_desc;
        if ($request->input('accident-cause')) {
            $dangerPoint->accident_cause = explode(',', $request->input('accident-cause')) ?? $dangerPoint->accident_cause;
        }
        $dangerPoint->accident_cause_suggest = $request->input('accident-cause-suggest') ?? $dangerPoint->accident_cause_suggest;
        if ($request->input('accident-severity')) {
            $dangerPoint->accident_severity = explode(',', $request->input('accident-severity')) ?? $dangerPoint->accident_severity;
        }
        $dangerPoint->accident_severity_suggest = $request->input('accident-severity-suggest') ??  $dangerPoint->accident_severity_suggest;
        $dangerPoint->correction_plan_done = $request->input('correction-plan-done') ?? $dangerPoint->correction_plan_done;
        $dangerPoint->correction_plan_doing = $request->input('correction-plan-doing') ?? $dangerPoint->correction_plan_doing;
        $dangerPoint->correction_plan_doing_desc = $request->input('correction-plan-doing-desc') ?? $dangerPoint->correction_plan_doing_des;
        $dangerPoint->correction_plan_doing_suggest = $request->input('correction-plan-doing-suggest') ?? $dangerPoint->correction_plan_doing_suggest;

        // $files_path = null;

        // if ($request->file('signature-file')) {
        //     $files_path = $request->file('signature-file')->storeAs(
        //         'public/danger-points/signature',
        //         'sign_' . time() . '_signature_file_' . $dangerPoint->id . '_' . $request->file('signature-file')->getClientOriginalName()
        //     );
        // }

        // $dangerPoint->signature_file = $files_path;

        $dangerPoint->save();

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

    public function updateDangerAccident(Request $request, $id)
    {
        $request->validate([
            'danger-id' => 'required|integer|exists:danger_points,id',
            'serial-number' => 'string|unique:danger_point_accidents,serial_number',
            'accident-date' => 'required|string',
            'day' => 'required|integer|between:1,7',
            'time' => 'required|string',
            'accident-direction' => 'required|integer|between:1,2',
            'collision-type' => 'required|integer|between:1,6',
            'accident-factors' => 'required|json',
            'accident-type' => 'required|integer|between:1,3',
            'accident-result' => 'required|json'
        ]);

        $dangerPointAccident = DangerPointAccident::find($id);

        $accDate = explode('-', $request->input('accident-date'));
        $accDateGregorian = Verta::getGregorian($accDate[0], $accDate[1], $accDate[2]);
        if (count($accDateGregorian) == 3) {
            $accDateGregorianSt = $accDateGregorian[0] . '-' . $accDateGregorian[1] . '-' .$accDateGregorian[2];
        } else {
            $accDateGregorianSt = null;
        }

        $dangerPointAccident->serial_number = $request->input('serial-number') ?? $dangerPointAccident->serial_number;
        $dangerPointAccident->accident_date = $accDateGregorianSt ?? $dangerPointAccident->accident_date;
        $dangerPointAccident->day = $request->input('day') ?? $dangerPointAccident->day;
        $dangerPointAccident->time = $request->input('time') ?? $dangerPointAccident->time;
        $dangerPointAccident->accident_direction = $request->input('accident-direction') ?? $dangerPointAccident->accident_direction;
        $dangerPointAccident->collision_type = $request->input('collision-type') ?? $dangerPointAccident->collision_type;
        if ($request->input('accident-factors')) {
            $dangerPointAccident->accident_factors = json_decode($request->input('accident-factors'));
        }
        $dangerPointAccident->accident_type = $request->input('accident-type') ?? $dangerPointAccident->accident_type;
        if ($request->input('accident-result')) {
            $dangerPointAccident->accident_result = json_decode($request->input('accident-result'));
        }

        $dangerPointAccident->save();

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

    public function getDangerPointPreview($id, $op = 'print')
    {
        $dangerPoint = DangerPoint::where('id', $id)->with('dangerPointAccidents')->get();

        $dayArray = [
            'شنبه',
            'یکشنبه',
            'دوشنبه',
            'سه‌شنبه',
            'چهارشنبه',
            'پنج‌شنبه',
            'جمعه'
        ];

        $collisionTypeArray = [
            'رخ به رخ',
            'واژگونی',
            'جلو به عقب',
            'جلو به پهلو',
            'برخورد با شی ثابت',
            'برخورد با عابر'
        ];

        $dangerAccidentsArray = [];
        $dangerAccidentsSum = [
            0, 0, 0, 0, 0
        ];

        foreach ($dangerPoint[0]->dangerPointAccidents as $key => $dangerAccident) {
            $dangerAccidentsArray[$key] = [
                'serial_number' => $dangerAccident->serial_number,
                'accident_day' => verta($dangerAccident->accident_date)->format('j'),
                'accident_month' => verta($dangerAccident->accident_date)->format('n'),
                'accident_year' => verta($dangerAccident->accident_date)->format('y'),
                'day' => $dayArray[$dangerAccident->day - 1],
                'time' => $dangerAccident->time,
                'accident_direction' => $dangerAccident->accident_direction,
                'collision_type' => $collisionTypeArray[$dangerAccident->collision_type - 1],
                'accident_factors' => $dangerAccident->accident_factors,
                'accident_type' => $dangerAccident->accident_type,
                'accident_result' => $dangerAccident->accident_result
            ];

            $dangerAccidentsSum[0] += ($dangerAccident->accident_type == 1) ? 1 : 0;
            $dangerAccidentsSum[1] += ($dangerAccident->accident_type == 2) ? 1 : 0;
            //$dangerAccidentsSum[2] += ($dangerAccident->accident_type == 3) ? 1 : 0;
            $dangerAccidentsSum[3] += $dangerAccident->accident_result['de'];
            $dangerAccidentsSum[4] += $dangerAccident->accident_result['in'];
        }

        $axisTypeArray = [
            'آزادراه',
            'بزرگراه',
            'راه اصلی',
            'راه فرعی با عملکرد اصلی',
            'راه فرعی (درجه 1 یا 2)',
            'راه روستایی (فرعی درجه 3)'
        ];

        $accidentPossibilityArray = [
            'خیر',
            'بله'
        ];

        $roadGuardArray = [
            'خیر',
            'بله'
        ];

        $accident251Array = [
            'خیر',
            'بله'
        ];

        $geometricDescArray = [
            'تقاطع',
            'پل',
            'قوس افقی',
            'قوس قائم',
            'قوس افقی و قائم',
            'تونل',
            'میدان',
            'تقاطع-قوس',
            'پل-قوس',
            'تونل-قوس',
            'پل-تقاطع',
            'پل-تقاطع-قوس',
            'منطقه مسکونی',
            'مسیر مستقیم فاقد راه دسترسی',
            'پل - تقاطع - منطقه مسکونی',
            'تقاطع - قوس - منطقه مسکونی'
        ];

        $accidentCauseArray = [
            'قوس تند افقی',
            'ابهام در مسیر (نقص در نحوه مسیرنمایی)',
            'عدم رعایت سرعت مجاز',
            'قوس تند قائم',
            'دید ناکافی (مثلث دید-مسافتدید توفق یا سبقت)',
            'عدم رعایت سبقت مجاز',
            'قرارگیری قوس افقی در تاج قوس قائم',
            '(جانمایی/طرح تابلو ) نقص در علائم پیش آگاهی و هدایت مسیر',
            'عدم رعایت محدودیت/ممنوعیت عبور',
            'قوس افقی در سرازیری تند',
            'نقص در علائم اخطاری و انتظامی',
            'عدم رعایت فاصله طولی',
            'هندسه نامناسب ورودی و خروجی دسترسی-تقاطع-دوربرگردان',
            'نقص در اشکارسازی نواحی انتقال قبل پل ها و تونل ها که شانه حذف میشود',
            'افتادگی در لبه آسفالت و یا فقدان شانه',
            'تبدیل نامناسب نوع راه (جدا شده به جدا نشده)',
            'عدم روشنایی ضروری در نقطه (محل عبور عرضی عمده عابرین یا خودرو ها)',
            'منطقه مه گیر /کولاک/یخ زدگی/شن زدگی',
            'منطقه با تداخل ترافیکی (نواحی مسکونی ،صنعتی،تفریحی،مدارس،و..)',
            'منطقه با عبور حیوانات اهلی / وحشی',
            'کاهش نامناسب تعداد خطوط (4 به 3 یا به 2)',
            'منطقه با افزایش ناگهانی تراکم ترافیک',
            'منطقه با ریزش از دیوار ترانشه',
            'نبود /نقص در خط سبقت در سربالایی برای وسایل نقلیه سنگین در نواحی ضروری',
            'دور مناسب در قوس',
            'نقص در آشکار سازی شرایط خاص یا غیر منتظره',
            'رویه نامناسب (ناهموار-قیرزده-صیقلی) یا آسیب دیده (وجود چاله )',
            'محل نامناسب دسترسی/دسترسی های متعدد و نا ایمن در حریم راه',
            'عرض کم سواره رو',
            'سرازیری تند'
        ];

        $accidentSeverityArray = [
            'شیروانی تند یا پرتگاه بدون حفاظت',
            'سر ازاد حفاظ',
            'مانع صلب بدون حفاظت در حاشیه راه',
            'نقص در ناحیه انتقالی اتصال انواع حفاظ (محل پل و ...)',
            'نقص یا عدم کفایت حفاظ کناری',
            'نقص یا عدم کفایت نرده پل',
            'نقص یا عدم کفایت حفاظ میانی',
            'فقدان جداکننده در میانه راه چهار خطه'
        ];

        $accidentCauseString = "";

        if ($dangerPoint[0]->accident_cause) {
            foreach ($dangerPoint[0]->accident_cause as $value) {
                $accidentCauseString .= ($accidentCauseArray[$value - 1] . ", ");
            }
        }

        $accidentSeverityString = "";

        if ($dangerPoint[0]->accident_severity != null) {
            foreach ($dangerPoint[0]->accident_severity as $value) {
                $accidentSeverityString .= ($accidentSeverityArray[$value - 1] . ", ");
            }
        }

        $dangerPointArray = [
            'created_at' => verta($dangerPoint[0]->created_at)->format('Y/m/d - H:m'),
            'updated_at' => verta($dangerPoint[0]->updated_at)->format('Y/m/d - H:m'),
            'province_name' => $dangerPoint[0]->province->name_fa,
            'axis_name' => $dangerPoint[0]->axis_name,
            'axis_type' => $axisTypeArray[$dangerPoint[0]->axis_type - 1],
            'axis_start' => $dangerPoint[0]->axis_start,
            'axis_end' => $dangerPoint[0]->axis_end,
            'distance_axis_start' => $dangerPoint[0]->distance_axis_start,
            'local_name' => $dangerPoint[0]->local_name,
            'lat_lng' => [
                $dangerPoint[0]->lat,
                $dangerPoint[0]->lng
            ],
            'speed_limit' => $dangerPoint[0]->speed_limit,
            'speed_average' => $dangerPoint[0]->speed_average,
            'accident_possibility' => $accidentPossibilityArray[$dangerPoint[0]->accident_possibility],
            'road_guard' => $roadGuardArray[$dangerPoint[0]->road_guard],
            'geometric_desc' => $geometricDescArray[$dangerPoint[0]->geometric_desc - 1],
            'accident_cause' => ((strlen($accidentCauseString) > 3) ? substr($accidentCauseString, 0, -2) : $accidentCauseString),
            'accident_cause_suggest' => $dangerPoint[0]->accident_cause_suggest,
            'accident_severity' => ((strlen($accidentSeverityString) > 3) ? substr($accidentSeverityString, 0, -2) : $accidentSeverityString),
            'accident_severity_suggest' => $dangerPoint[0]->accident_severity_suggest,
            'correction_plan_done' => $dangerPoint[0]->correction_plan_done,
            'correction_plan_doing' => $dangerPoint[0]->correction_plan_doing,
            'correction_plan_doing_desc' => $dangerPoint[0]->correction_plan_doing_desc,
            'correction_plan_doing_suggest' => $dangerPoint[0]->correction_plan_doing_suggest,
            'accident_251' => $accident251Array[$dangerPoint[0]->accident_251],
            'accident_251_code' => $dangerPoint[0]->accident_251_code,
            'danger_point_accidents' => $dangerAccidentsArray,
            'danger_accidents_sum' => $dangerAccidentsSum
        ];
    
        if ($op == 'print') {
            $pdf = SnappyPdf::loadView('rmto-preview.pages.danger-point-preview', ['dangerPointArray' => $dangerPointArray]);
            
            return $pdf->download('danger-points-id-' . $dangerPoint[0]->id . '.pdf');
        } else {
            return response()->json([
                'status' => 'succeed',
                'message' => '',
                'data' => $dangerPointArray
            ], 200);
        }
    }

    public function uploadDangerPointFiles(Request $request)
    {
        $request->validate([
            'danger-id' => 'required|integer|exists:danger_points,id',
            'signature-file' => 'image',
            'police-file' => 'image'
        ]);

        $dangerPoint = DangerPoint::find($request->input('danger-id'));

        if ($request->file('signature-file')) {
            $signature_file = $request->file('signature-file')->storeAs(
                'public/danger_points',
                'file_signature-file_' . $dangerPoint->id . '_' . time() . '_' . $request->file('signature-file')->getClientOriginalName()
            );

            $dangerPoint->signature_file = $signature_file;
        }

        if ($request->file('police-file')) {
            $police_file = $request->file('police-file')->storeAs(
                'public/danger_points',
                'file_police-file_' . $dangerPoint->id . '_' . time() . '_' . $request->file('police-file')->getClientOriginalName()
            );
        
            $dangerPoint->police_file = $police_file;
        }

        $dangerPoint->save();

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

    public function destroyDangerFilesImage(Request $request)
    {
        $request->validate([
            'danger-id' => 'required|integer|exists:danger_points,id',
            'name' => 'required|string'
        ]);

        $dangerPoint = DangerPoint::find($request->input('danger-id'));

        if ($request->input('name') == 'signature-file') {
            $dangerPoint->signature_file = null;
        } elseif ($request->input('name') == 'police-file') {
            $dangerPoint->police_file = null;
        }

        $dangerPoint->save();

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

    public function provinceFinalSubmit(Request $request)
    {
        $request->validate([
            'danger-id' => 'required|integer|exists:danger_points,id'
        ]);

        $dangerPoint = DangerPoint::find($request->input('danger-id'));

        $dangerPoint->status = 1;
        $dangerPoint->created_at = Carbon::now();

        $dangerPoint->save();

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

    public function destroyDanger($id)
    {
        $dangerPoint = DangerPoint::find($id);
        
        $dangerPoint->dangerPointHistories()->delete();
        $dangerPoint->dangerPointAccidents()->delete();
        $dangerPoint->files()->delete();
        $dangerPoint->delete();

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

    public function adminSubmitStatus(Request $request)
    {
        $request->validate([
            'danger-id' => 'required|integer|exists:danger_points,id',
            'status' => 'required|integer|between:2,4',
            'status-desc' => 'required_if:danger-status,3'
        ]);

        $dangerPoint = DangerPoint::find($request->input('danger-id'));

        $dangerPoint->status = $request->input('status');

        if ($request->input('status-desc') && $request->input('status') == 3) {
            $dangerPoint->status_desc = $request->input('status-desc');
        }

        if ($request->input('status') == 2) {
            $provincesCode = [
                3 => [
                  "province_id" => 3,
                  "province_name" => "اردبیل",
                  "province_code" => 9199
                ],
                4 => [
                  "province_id" => 4,
                  "province_name" => "اصفهان",
                  "province_code" => 2199
                ],
                5 => [
                  "province_id" => 5,
                  "province_name" => "البرز",
                  "province_code" => 1899
                ],
                6 => [
                  "province_id" => 6,
                  "province_name" => "ايرانشهر",
                  "province_code" => 6299
                ],
                7 => [
                  "province_id" => 7,
                  "province_name" => "ايلام ",
                  "province_code" => 8399
                ],
                2 => [
                  "province_id" => 2,
                  "province_name" => "آذربايجان غربي",
                  "province_code" => 5799
                ],
                1 => [
                  "province_id" => 1,
                  "province_name" => "آذربایجان شرقی",
                  "province_code" => 2699
                ],
                8 => [
                  "province_id" => 8,
                  "province_name" => "بوشهر",
                  "province_code" => 9599
                ],
                9 => [
                  "province_id" => 9,
                  "province_name" => "تهران",
                  "province_code" => 1199
                ],
                10 => [
                  "province_id" => 10,
                  "province_name" => "چهارمحال و بختياري",
                  "province_code" => 7799
                ],
                11 => [
                  "province_id" => 11,
                  "province_name" => "خراسان جنوبی",
                  "province_code" => 3399
                ],
                12 => [
                  "province_id" => 12,
                  "province_name" => "خراسان رضوي",
                  "province_code" => 3199
                ],
                13 => [
                  "province_id" => 13,
                  "province_name" => "خراسان شمالی",
                  "province_code" => 3299
                ],
                14 => [
                  "province_id" => 14,
                  "province_name" => "خوزستان",
                  "province_code" => 3699
                ],
                15 => [
                  "province_id" => 15,
                  "province_name" => "زنجان",
                  "province_code" => 6799
                ],
                17 => [
                  "province_id" => 17,
                  "province_name" => "سمنان",
                  "province_code" => 8799
                ],
                16 => [
                  "province_id" => 16,
                  "province_name" => "سمنان شرق",
                  "province_code" => 8899
                ],
                18 => [
                  "province_id" => 18,
                  "province_name" => "سيستان و بلوچستان",
                  "province_code" => 6199
                ],
                19 => [
                  "province_id" => 19,
                  "province_name" => "فارس",
                  "province_code" => 4199
                ],
                20 => [
                  "province_id" => 20,
                  "province_name" => "قزوین",
                  "province_code" => 1599
                ],
                21 => [
                  "province_id" => 21,
                  "province_name" => "قم",
                  "province_code" => 1499
                ],
                25 => [
                  "province_id" => 25,
                  "province_name" => "كرمانشاه",
                  "province_code" => 7199
                ],
                22 => [
                  "province_id" => 22,
                  "province_name" => "کردستان",
                  "province_code" => 7399
                ],
                23 => [
                  "province_id" => 23,
                  "province_name" => "کرمان",
                  "province_code" => 4599
                ],
                24 => [
                  "province_id" => 24,
                  "province_name" => "کرمان جنوب",
                  "province_code" => 4699
                ],
                26 => [
                  "province_id" => 26,
                  "province_name" => "کهگیلویه و بویراحمد",
                  "province_code" => 8599
                ],
                27 => [
                  "province_id" => 27,
                  "province_name" => "گلستان",
                  "province_code" => 9799
                ],
                28 => [
                  "province_id" => 28,
                  "province_name" => "گیلان",
                  "province_code" => 5499
                ],
                29 => [
                  "province_id" => 29,
                  "province_name" => "لارستان",
                  "province_code" => 2999
                ],
                30 => [
                  "province_id" => 30,
                  "province_name" => "لرستان",
                  "province_code" => 8199
                ],
                31 => [
                  "province_id" => 31,
                  "province_name" => "مازندران",
                  "province_code" => 1699
                ],
                32 => [
                  "province_id" => 32,
                  "province_name" => "مركزي",
                  "province_code" => 5199
                ],
                33 => [
                  "province_id" => 33,
                  "province_name" => "هرمزگان",
                  "province_code" => 6499
                ],
                34 => [
                  "province_id" => 34,
                  "province_name" => "همدان",
                  "province_code" => 7599
                ],
                35 => [
                  "province_id" => 35,
                  "province_name" => "يزد",
                  "province_code" => 9399
                ]
            ];

            $dangerPoints = DangerPoint::where('province_id', $dangerPoint->province_id)
                ->where('status', 2)
                ->orderByDesc('code')
                ->limit(1)
                ->get();

            if ($dangerPoints->count() == 1) {
                $dangerPoint->code = $dangerPoints[0]->code + 1;
            } else {
                $dangerPoint->code = $provincesCode[$dangerPoint->province_id]['province_code'] . '001';
            }
        }

        $dangerPoint->save();

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

    public function addNewUsers()
    {
        $users = \App\Models\User::where('username', 'like', '%imenivaharim%')
            ->get();

        //dd($users);

        foreach ($users as $user) {
            $newUser1 = new \App\Models\User;
            $newUser2 = new \App\Models\User;

            $newUser1->username = $user->username . '1';
            $newUser2->username = $user->username . '2';
            $newUser1->name = 'کارشناس ایمنی و حریم';
            $newUser2->name = 'کارشناس ایمنی و حریم';
            $newUser1->province_id = $user->province_id;
            $newUser2->province_id = $user->province_id;
            $newUser1->password = Hash::make('123');
            $newUser2->password = Hash::make('123');

            // $newUser1->save();
            // $newUser2->save();
        }
    }
    public function danger_points_result(Request $request)
    {
        // $results = DB::select( DB::raw("SELECT ROW_NUMBER() OVER() AS r,p,a,l,c,e,g,f,b,i,d,s,
        // CAST(ROUND((s-ag)/sd,2)AS DEC(10,2)) AS zi,0 AS pp,CAST(ROUND(ag,2) AS DEC(10,2)) AS ag,
        // CAST(ROUND(sd,2) AS DEC(10,2)) AS sd,j,h FROM (SELECT *,SUM(d*5 + i) AS s FROM
        // (SELECT danger_points.id AS z, axis_name AS a, axis_type_fa AS b, axis_start AS c,
        // axis_end AS e, distance_axis_start AS f, local_name AS l, lat AS j,lng AS h,
        // geometric_desc_fa AS g, SUM(JSON_UNQUOTE(JSON_EXTRACT(accident_result,\"$.de\"))) AS d,
        // SUM(JSON_UNQUOTE(JSON_EXTRACT(accident_result,\"$.in\"))) AS i, province_fa AS p FROM danger_points
        // JOIN danger_point_accidents ON danger_points.id = danger_point_accidents.`point_id` GROUP BY z) q,
        // (SELECT AVG(s) AS ag ,STDDEV(s) AS sd FROM (SELECT *,SUM(d*5 + i) AS s FROM (SELECT danger_points.id AS z,
        // axis_name AS a, axis_type_fa AS b, axis_start AS c, axis_end AS e, distance_axis_start AS f, local_name AS l,
        // lat AS j,lng AS h, geometric_desc_fa AS g, SUM(JSON_UNQUOTE(JSON_EXTRACT(accident_result,\"$.de\"))) AS d,
        // SUM(JSON_UNQUOTE(JSON_EXTRACT(accident_result,\"$.in\"))) AS i, province_fa AS p FROM danger_points JOIN
        // danger_point_accidents ON danger_points.id = danger_point_accidents.`point_id` GROUP BY z) q GROUP BY z) m)
        // AS totals GROUP BY z) wqwq") );
        // $results = DB::select( DB::raw("SELECT r,p,a,l,c,e,g,f,b,i,d,s,CAST(ROUND((s-ag)/sd,2)AS DEC(10,2)) AS zi,
        // CAST(gauss_cdf(ag,sd,s)AS DEC(10,2)) AS pp,CAST(ROUND(ag,2) AS DEC(10,2)) AS ag
        // ,CAST(ROUND(sd,2) AS DEC(10,2)) AS sd ,j,h FROM (SELECT *,i+d*5 AS s,AVG(i+d*5) AS ag,STDDEV(i+d*5) AS sd
        //  FROM (SELECT COUNT( CASE WHEN accident_type = 1 THEN 1 ELSE NULL END) AS i,
        // COUNT( CASE WHEN accident_type = 2 THEN 1 ELSE NULL END) AS d,geometric_desc_fa AS g,
        // axis_type_fa AS b,danger_points.code AS cd, province_fa AS p,danger_points.code AS r,
        // axis_name AS a, axis_start AS c, axis_end AS e, distance_axis_start AS f, local_name AS l,
        // lat AS j,lng AS h FROM danger_points JOIN danger_point_accidents
        // ON danger_point_accidents.`point_id` = danger_points.id
        // GROUP BY danger_points.code)asd GROUP BY g,b) aas INNER JOIN danger_points ON
        // danger_points.`geometric_desc_fa` = aas.g
        // AND danger_points.`axis_type_fa` = aas.b WHERE danger_points.code <> ''") );
        $results = DB::select(DB::raw("SELECT 
        tablea.cd,tablea.p,tablea.a,tablea.l,tablea.c,tablea.e,tablea.g,tablea.f,tablea.b,tablea.i,tablea.d,
        tablea.s,tableb.ag,tableb.sd,CAST(ROUND((s-ag)/sd,2)AS DEC(10,2)) AS zi,
        CAST(gauss_cdf(ag,sd,s)AS DEC(10,2)) AS pp,tablea.j AS j,tablea.h AS h
         FROM (
        SELECT s,i,d,g,b,cd,l,p,a,c,e,f,j,h FROM 
        (SELECT COUNT( CASE WHEN accident_type = 1 THEN 1 ELSE NULL END) 
        + 5*COUNT( CASE WHEN accident_type = 2 THEN 1 ELSE NULL END) AS s,
         COUNT( CASE WHEN accident_type = 1 THEN 1 ELSE NULL END) AS i, 
        COUNT( CASE WHEN accident_type = 2 THEN 1 ELSE NULL END) AS d,geometric_desc_fa AS g,
        axis_type_fa AS b,danger_points.code AS cd, province_fa AS p,
        axis_name AS a, axis_start AS c, axis_end AS e, distance_axis_start AS f, local_name AS l,
        lat AS j,lng AS h FROM danger_points JOIN danger_point_accidents
        ON danger_point_accidents.`point_id` = danger_points.id  WHERE danger_points.code <>''
        GROUP BY danger_points.code,danger_points.`geometric_desc_fa`,danger_points.`axis_type_fa`)asd
         GROUP BY asd.cd,asd.g,asd.b) AS tablea JOIN (SELECT CAST(ROUND(ag,2) AS DEC(10,2)) AS ag
        ,CAST(ROUND(sd,2) AS DEC(10,2)) AS sd,danger_points.code AS cd,p,l,f,a,e,c,j,h
         FROM (SELECT *,i+d*5 AS s,AVG(i+d*5) AS ag,STDDEV(i+d*5) AS sd
         FROM (SELECT COUNT( CASE WHEN accident_type = 1 THEN 1 ELSE NULL END) AS i, 
        COUNT( CASE WHEN accident_type = 2 THEN 1 ELSE NULL END) AS d,geometric_desc_fa AS g,
        axis_type_fa AS b,danger_points.code AS cd, province_fa AS p,danger_points.code AS z,
        axis_name AS a, axis_start AS c, axis_end AS e, distance_axis_start AS f, local_name AS l,
        lat AS j,lng AS h FROM danger_points JOIN danger_point_accidents
        ON danger_point_accidents.`point_id` = danger_points.id  
        GROUP BY danger_points.code)asd GROUP BY g,b) aas INNER JOIN danger_points ON 
        danger_points.`geometric_desc_fa` = aas.g 
        AND danger_points.`axis_type_fa` = aas.b WHERE danger_points.code <> '' ) AS tableb ON tablea.cd = tableb.cd
        "));
        
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $results
        ], 200);
        return $results;
        $danger_points = DangerPoint::all();
        // return $danger_points;
        // $data = (object)[];
        foreach ($danger_points as $value) {
            $de = 0;
            $in = 0;
            // $accidents = $value->dangerPointAccidents;
            $value->de = 0;
            $value->in = 0;
            $value->de = 0;
            $value->in = 0;
            foreach ($value->dangerPointAccidents as $valueAccs) {
                // echo gettype(json_decode($valueAccs->accident_result));
                // $temp = json_encode($valueAccs->accident_result);
                // echo $temp->de."\n";
                $de += ($valueAccs->accident_result['de'] > 0) ?$valueAccs->accident_result['de'] :0;
                $in += ($valueAccs->accident_result['in'] > 0) ?$valueAccs->accident_result['in'] :0;
            }
            $value->de = $de;
            $value->in = $in;
            $de = 0;
            $in = 0;
            unset($value->dangerPointAccidents);
            // unset($value->id);
            unset($value->code);
            unset($value->user_id);
            unset($value->province_id);
            unset($value->city_id);
            unset($value->axis_type);
            unset($value->accident_251);
            unset($value->accident_251_code);
            unset($value->speed_limit);
            unset($value->speed_average);
            unset($value->accident_possibility);
            unset($value->road_guard);
            unset($value->geometric_desc);
            unset($value->accident_cause);
            unset($value->accident_cause_suggest);
            unset($value->accident_severity);
            unset($value->accident_severity_suggest);
            unset($value->correction_plan_done);
            unset($value->correction_plan_doing);
            unset($value->correction_plan_doing_desc);
            unset($value->correction_plan_doing_suggest);
            unset($value->signature_file);
            unset($value->police_file);
            unset($value->signature_file);
            unset($value->status);
            unset($value->status_desc);
            unset($value->created_at);
            unset($value->updated_at);
            unset($value->accident_sigma_2);
            unset($value->accident_sigma);
            unset($value->standard_deviation);
            unset($value->accident_avg_weighted_average);
            unset($value->accident_p);
            unset($value->accident_zi);
            unset($value->weighted_average);
            unset($value->accident_result_de);
            unset($value->accident_result_in);
            /*
    "province_fa": null,
    "axis_name": "سیرجان - بافت",
    "axis_type_fa": null,
    "axis_start": "سیرجان",
    "axis_end": "بافت",
    "distance_axis_start": "10",
    "local_name": "پیچ قطبیه",
    "lat": "29.386943",
    "lng": "55.779487",
    "geometric_desc_fa": null,
    "accident_result_de": null,
    "accident_result_in": null,
    "weighted_average": null,
    "accident\u001f_zi": null,
    "accident_p": null,
    "accident_avg_weighted_average": null,
    "standard_deviation": null,
    "accident_sigma": null,
    "accident_sigma_2": null,
    "created_at": "2020-09-10 07:59:08",
    "updated_at": "2020-09-12 13:53:36",
    "de": 3,
    "in": 20
            */
        }
        // dd($data);
        // $danger = get_object_vars($danger_points);
        // unset($danger['danger_point_accidents']);
        return $danger_points;
        // return $danger_points->makeHidden('danger_point_accidents')->toArray();
        /*
        if (data.axis_type == 1) {
            return "ازادراه";
          } else if (data.axis_type == 2) {
            return "بزرگراه";
          } else if (data.axis_type == 3) {
            return " راه اصلی";
          } else if (data.axis_type == 4) {
            return "راه فرعی با عملکرد اصلی ";
          } else if (data.axis_type == 5) {
            return "راه فرعی (درجه 1 یا 2)";
          } else if (data.axis_type == 6) {
            return "راه روستایی (درجه 3)";
          }*/
        $dangerAccidents = DangerPoint::find($id)->dangerPointAccidents;

        $dangerAccidentsArray = [];

        foreach ($dangerAccidents as $key => $dangerAccident) {
            $dangerAccidentsArray[$key] = [
                'id' => $dangerAccident->id,
                'serial_number' => $dangerAccident->serial_number,
                'accident_date' => (($dangerAccident->accident_date) ? verta($dangerAccident->accident_date)->format('Y/m/d') : $dangerAccident->accident_date),
                'day' => $dangerAccident->day,
                'time' => $dangerAccident->time,
                'accident_direction' => $dangerAccident->accident_direction,
                'collision_type' => $dangerAccident->collision_type,
                'accident_factors' => $dangerAccident->accident_factors,
                'accident_type' => $dangerAccident->accident_type ?? [],
                'accident_result' => $dangerAccident->accident_result
            ];
        }

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $dangerAccidentsArray
        ], 200);
    }
    public function danger_points_result_chart(Request $request)
    {
        $data=DB::select(DB::raw("SELECT g,b,CAST(ROUND(ag,2) AS DEC(10,2)) AS s FROM (SELECT *,i+d*5 AS s,AVG(i+d*5) AS ag,STDDEV(i+d*5) AS sd
        FROM (SELECT COUNT( CASE WHEN accident_type = 1 THEN 1 ELSE NULL END) AS i, 
       COUNT( CASE WHEN accident_type = 2 THEN 1 ELSE NULL END) AS d,geometric_desc_fa AS g,
       axis_type_fa AS b,danger_points.code AS cd, province_fa AS p,danger_points.code AS z,
       axis_name AS a, axis_start AS c, axis_end AS e, distance_axis_start AS f, local_name AS l,
       lat AS j,lng AS h FROM danger_points JOIN danger_point_accidents
       ON danger_point_accidents.`point_id` = danger_points.id  
       GROUP BY danger_points.code)asd GROUP BY g,b) aas INNER JOIN danger_points ON 
       danger_points.`geometric_desc_fa` = aas.g 
       AND danger_points.`axis_type_fa` = aas.b WHERE danger_points.code <> '' GROUP BY g,b order by ag desc"));
        $avg = DB::select(DB::raw("SELECT AVG(s) AS ag FROM (SELECT g,b,CAST(ROUND(ag,2) AS DEC(10,2)) AS s FROM (SELECT *,i+d*5 AS s,AVG(i+d*5) AS ag,STDDEV(i+d*5) AS sd
        FROM (SELECT COUNT( CASE WHEN accident_type = 1 THEN 1 ELSE NULL END) AS i, 
       COUNT( CASE WHEN accident_type = 2 THEN 1 ELSE NULL END) AS d,geometric_desc_fa AS g,
       axis_type_fa AS b,danger_points.code AS cd, province_fa AS p,danger_points.code AS z,
       axis_name AS a, axis_start AS c, axis_end AS e, distance_axis_start AS f, local_name AS l,
       lat AS j,lng AS h FROM danger_points JOIN danger_point_accidents
       ON danger_point_accidents.`point_id` = danger_points.id  
       GROUP BY danger_points.code)asd GROUP BY g,b) aas INNER JOIN danger_points ON 
       danger_points.`geometric_desc_fa` = aas.g 
       AND danger_points.`axis_type_fa` = aas.b WHERE danger_points.code <> '' GROUP BY g,b)asd"));
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $data,
            'avg' =>$avg
        ], 200);
    }
    public function danger_points_result_new(Request $request)
    {
        $data=DB::select(DB::raw("SELECT 
        tablea.cd,tablea.p,tablea.a,tablea.l,tablea.c,tablea.e,tablea.g,tablea.gg,tablea.f,tablea.b,tablea.bb,tablea.i,tablea.d,tablea.s,tableb.ag,tableb.sd,CAST(ROUND((s-ag)/sd,2)AS DEC(10,2)) AS zi,
        CAST(gauss_cdf(ag,sd,s)AS DEC(10,2)) AS pp,tablea.j AS j,tablea.h AS h
         FROM (
        SELECT s,i,d,g,gg,b,bb,cd,l,p,a,c,e,f,j,h FROM 
        (SELECT COUNT( CASE WHEN accident_type = 1 THEN 1 ELSE NULL END) + 5*COUNT( CASE WHEN accident_type = 2 THEN 1 ELSE NULL END) AS s, COUNT( CASE WHEN accident_type = 1 THEN 1 ELSE NULL END) AS i, 
        COUNT( CASE WHEN accident_type = 2 THEN 1 ELSE NULL END) AS d,geometric_desc_fa AS g,
        CASE WHEN geometric_desc=11 OR geometric_desc=15 THEN 'پل - تقاطع' 
	WHEN geometric_desc = 16 OR geometric_desc = 12 OR geometric_desc=8 THEN 'تقاطع - قوس'
	WHEN geometric_desc = 10 OR geometric_desc = 5 OR geometric_desc = 4 OR geometric_desc=3 THEN 'قوس های افقی و قائم'
	WHEN geometric_desc=14 THEN 'نقطه عادی'
	WHEN geometric_desc=13 OR geometric_desc=1 THEN 'تقاطع'
        ELSE geometric_desc_fa END AS gg,
        CASE WHEN axis_type = 4 OR axis_type = 5 OR axis_type = 6 THEN 'راه فرعی' 
ELSE axis_type_fa END AS bb,
        axis_type_fa AS b,danger_points.code AS cd, province_fa AS p,
        axis_name AS a, axis_start AS c, axis_end AS e, distance_axis_start AS f, local_name AS l,
        lat AS j,lng AS h FROM danger_points JOIN danger_point_accidents
        ON danger_point_accidents.`point_id` = danger_points.id  WHERE danger_points.code <>''
        GROUP BY danger_points.code,gg,bb)asd GROUP BY asd.cd,asd.gg,asd.bb) AS tablea JOIN (SELECT CAST(ROUND(ag,2) AS DEC(10,2)) AS ag
        ,CAST(ROUND(sd,2) AS DEC(10,2)) AS sd,danger_points.code AS cd,p,l,f,a,e,c,j,h FROM (SELECT *,i+d*5 AS s,AVG(i+d*5) AS ag,STDDEV(i+d*5) AS sd
         FROM (SELECT COUNT( CASE WHEN accident_type = 1 THEN 1 ELSE NULL END) AS i, 
        COUNT( CASE WHEN accident_type = 2 THEN 1 ELSE NULL END) AS d,geometric_desc_fa AS g,
        CASE WHEN geometric_desc=11 OR geometric_desc=15 THEN 'پل - تقاطع' 
	WHEN geometric_desc = 16 OR geometric_desc = 12 OR geometric_desc=8 THEN 'تقاطع - قوس'
	WHEN geometric_desc = 10 OR geometric_desc = 5 OR geometric_desc = 4 OR geometric_desc=3 THEN 'قوس های افقی و قائم'
	WHEN geometric_desc=14 THEN 'نقطه عادی'
	WHEN geometric_desc=13 OR geometric_desc=1 THEN 'تقاطع'
        ELSE geometric_desc_fa END AS gg,
        CASE WHEN axis_type = 4 OR axis_type = 5 OR axis_type = 6 THEN 'راه فرعی' 
ELSE axis_type_fa END AS bb,
        axis_type_fa AS b,danger_points.code AS cd, province_fa AS p,danger_points.code AS z,
        axis_name AS a, axis_start AS c, axis_end AS e, distance_axis_start AS f, local_name AS l,
        lat AS j,lng AS h FROM danger_points JOIN danger_point_accidents
        ON danger_point_accidents.`point_id` = danger_points.id  
        GROUP BY danger_points.code)asd GROUP BY gg,bb) aas INNER JOIN danger_points ON 
        danger_points.n_geometric_desc_fa = aas.gg 
        AND danger_points.n_axis_type_fa = aas.bb WHERE danger_points.code <> '' ) AS tableb ON tablea.cd = tableb.cd"));
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $data,
        ], 200);
    }
    public function get_danger_report_danesh()
    {
        /*$sql = "SELECT * FROM danger_points JOIN danger_point_accidents ON
                danger_points.`id` = danger_point_accidents.`point_id` limit 100";
        $data=DB::select( DB::raw($sql));*/
        $data = DangerPoint::join('danger_point_accidents', 'danger_points.id', '=', 'danger_point_accidents.point_id')
                           ->get();
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $data,
        ], 200);
    }
}
