<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Hekmatinasser\Verta\Verta;
use App\Models\RoadUpgradeSafety;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class RoadUpgradeSafetyPublicController extends Controller
{
    public function getUpgradeSafetyList()
    {
        if (Auth::user()->hasRole('superadmin')  ||  Auth::user()->hasRole('management')  || Auth::user()->hasRole('witel') || Auth::user()->hasRole('admin')  || Auth::user()->hasRole('modiran') || Auth::user()->hasRole('setadi')) {
            $roadProjects = RoadUpgradeSafety::with('latestHistory')->get();
        } else {
            $roadProjects = RoadUpgradeSafety::with('latestHistory')
                                            ->where('province_id', Auth::user()->province_id)
                                            ->get();
        }
        
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $roadProjects,
            // 'can_submit' => (((Auth::user()->id < 36) || Auth::user()->hasRole('witel') || Auth::user()->hasRole('admin') || Auth::user()->hasRole('edaratostani') || Auth::user()->hasRole('setadi')) ? 1 : 0)
            'can_submit' => 1
        ], 200);
        $roadProjectsArray = [];

        foreach ($roadProjects as $key => $roadProject) {
            $cities = [];
            $citiesIndex = 0;

            foreach ($roadProject->cities_id as $cityKey => $value) {
                $getCity = \App\Models\City::find($cityKey);

                $cities[$citiesIndex] = [
                    'id' => $getCity->id,
                    'name' => $getCity->name_fa,
                    'value' =>  $value
                ];

                $citiesIndex++;
            }

            $roadProjectHistories = $roadProject->projectHistories;
    
            $roadProjectHistoriesFiles = [];
            $roadProjectHistoriesFilesDates = [];
            $imagesIndex = 0;
    
            foreach ($roadProjectHistories as $historyKey => $roadProjectHistoryValue) {
                foreach ($roadProjectHistoryValue->files as $keyPath => $file) {
                    $roadProjectHistoriesFiles[$imagesIndex] = asset('storage' . substr($file->path, 6));
                    $roadProjectHistoriesFilesDates[$imagesIndex] = verta($file->created_at)->format('Y/n/j - H:i');
                    $imagesIndex++;
                }
            }
    
            $roadProjectHistory = $roadProject->projectHistories()->latest()
                ->where('road_upgrade_safety_histories.previous_status', 1)
                ->first();

            $roadProjectsArray[$key] = [
                'id' => $roadProject->id,
                'province' => [
                    'id' => ($roadProject->province) ? $roadProject->province->id : null,
                    'name' => ($roadProject->province) ? $roadProject->province->name_fa : '-'
                ],
                'cities' => $cities,
                'axis_name' => ($roadProject->axis_name) ? $roadProject->axis_name : '-',
                'axis_type' => ($roadProject->axis_type) ? $roadProject->axis_type : 0,
                'project_name' => ($roadProject->project_name) ? $roadProject->project_name : '-',
                'contractor_name' => ($roadProject->contractor_name) ? $roadProject->contractor_name : '-',
                'consultant_name' => ($roadProject->consultant_name) ? $roadProject->consultant_name : '-',
                'contract_date' => ($roadProject->contract_date) ?$roadProject->contract_date :'-',
                'contract_credit' => ($roadProject->contract_credit) ? $roadProject->contract_credit : '-',
                'submited_at' => ($roadProject->submited_at) ?
                    verta($roadProject->submited_at)->format('Y/n/j - H:i') : '-',
                'last_updated_at' => ($roadProject->last_updated_at) ?
                    verta($roadProject->last_updated_at)->format('Y/n/j - H:i') : '-',
                'start_latlng' => $roadProject->start_latlng,
                'end_latlng' => $roadProject->end_latlng,
                'project_distance' => $roadProject->project_distance,
                'project_distance_update' => $roadProject->project_distance_update,
                'btn_status' => [
                    (($roadProject->project_distance) ? 1 : 0),
                    (($roadProject->status == 1) ? 1 : 0),
                    (($roadProject->status == 2) ? 0 : 1)
                ],
                'status' => $roadProject->status,
                'project_description' => $roadProject->project_description,
                'last_history' => (($roadProjectHistory) ? [
                    'last_updated_at' => verta($roadProjectHistory->updated_at)->format('Y/n/j - H:i'),
                    'last_project_status' => $roadProjectHistory->previous_project_status,
                    'status' => $roadProjectHistory->previous_status,
                    'updated_at_ge' => $roadProjectHistory->updated_at
                ] : [
                    'last_updated_at' => '-',
                    'last_project_status' => '-',
                    'status' => '-'
                ]),
                'images' => $roadProjectHistoriesFiles,
                'images_dates' => $roadProjectHistoriesFilesDates
            ];
        }

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $roadProjectsArray,
            'can_submit' => (((Auth::user()->id < 36) || Auth::user()->hasRole('witel') || Auth::user()->hasRole('admin') || Auth::user()->hasRole('edaratostani')) ? 1 : 0)
        ], 200);
    }
    public function getUpgradeSafetyListPublic()
    {
        // $per = ((Auth::user()->hasRole('witel') || Auth::user()->hasRole('admin') || Auth::user()->hasRole('modiran') || Auth::user()->hasRole('setadi') ) ? 1 : 0);
        // if ($per == 1)
        $roadProjects = RoadUpgradeSafety::with('latestHistory')->get();
        // else
        //     $roadProjects = RoadUpgradeSafety::with('latestHistory')
        //                                         ->where('province_id', Auth::user()->province_id)
        //                                          ->get();
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $roadProjects,
            // 'can_submit' => (((Auth::user()->id < 36) || Auth::user()->hasRole('witel') || Auth::user()->hasRole('admin') || Auth::user()->hasRole('edaratostani') || Auth::user()->hasRole('setadi')) ? 1 : 0)
            'can_submit' => 1
        ], 200);
        $roadProjectsArray = [];

        foreach ($roadProjects as $key => $roadProject) {
            $cities = [];
            $citiesIndex = 0;

            foreach ($roadProject->cities_id as $cityKey => $value) {
                $getCity = \App\Models\City::find($cityKey);

                $cities[$citiesIndex] = [
                    'id' => $getCity->id,
                    'name' => $getCity->name_fa,
                    'value' =>  $value
                ];

                $citiesIndex++;
            }

            $roadProjectHistories = $roadProject->projectHistories;
    
            $roadProjectHistoriesFiles = [];
            $roadProjectHistoriesFilesDates = [];
            $imagesIndex = 0;
    
            foreach ($roadProjectHistories as $historyKey => $roadProjectHistoryValue) {
                foreach ($roadProjectHistoryValue->files as $keyPath => $file) {
                    $roadProjectHistoriesFiles[$imagesIndex] = asset('storage' . substr($file->path, 6));
                    $roadProjectHistoriesFilesDates[$imagesIndex] = verta($file->created_at)->format('Y/n/j - H:i');
                    $imagesIndex++;
                }
            }
    
            $roadProjectHistory = $roadProject->projectHistories()->latest()
                ->where('road_upgrade_safety_histories.previous_status', 1)
                ->first();

            $roadProjectsArray[$key] = [
                'id' => $roadProject->id,
                'province' => [
                    'id' => ($roadProject->province) ? $roadProject->province->id : null,
                    'name' => ($roadProject->province) ? $roadProject->province->name_fa : '-'
                ],
                'cities' => $cities,
                'axis_name' => ($roadProject->axis_name) ? $roadProject->axis_name : '-',
                'axis_type' => ($roadProject->axis_type) ? $roadProject->axis_type : 0,
                'project_name' => ($roadProject->project_name) ? $roadProject->project_name : '-',
                'contractor_name' => ($roadProject->contractor_name) ? $roadProject->contractor_name : '-',
                'consultant_name' => ($roadProject->consultant_name) ? $roadProject->consultant_name : '-',
                'contract_date' => ($roadProject->contract_date) ?$roadProject->contract_date :'-',
                'contract_credit' => ($roadProject->contract_credit) ? $roadProject->contract_credit : '-',
                'submited_at' => ($roadProject->submited_at) ?
                    verta($roadProject->submited_at)->format('Y/n/j - H:i') : '-',
                'last_updated_at' => ($roadProject->last_updated_at) ?
                    verta($roadProject->last_updated_at)->format('Y/n/j - H:i') : '-',
                'start_latlng' => $roadProject->start_latlng,
                'end_latlng' => $roadProject->end_latlng,
                'project_distance' => $roadProject->project_distance,
                'project_distance_update' => $roadProject->project_distance_update,
                'btn_status' => [
                    (($roadProject->project_distance) ? 1 : 0),
                    (($roadProject->status == 1) ? 1 : 0),
                    (($roadProject->status == 2) ? 0 : 1)
                ],
                'status' => $roadProject->status,
                'project_description' => $roadProject->project_description,
                'last_history' => (($roadProjectHistory) ? [
                    'last_updated_at' => verta($roadProjectHistory->updated_at)->format('Y/n/j - H:i'),
                    'last_project_status' => $roadProjectHistory->previous_project_status,
                    'status' => $roadProjectHistory->previous_status,
                    'updated_at_ge' => $roadProjectHistory->updated_at
                ] : [
                    'last_updated_at' => '-',
                    'last_project_status' => '-',
                    'status' => '-'
                ]),
                'images' => $roadProjectHistoriesFiles,
                'images_dates' => $roadProjectHistoriesFilesDates
            ];
        }

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $roadProjectsArray,
            'can_submit' => (((Auth::user()->id < 36) || Auth::user()->hasRole('witel') || Auth::user()->hasRole('admin') || Auth::user()->hasRole('edaratostani')) ? 1 : 0)
        ], 200);
    }

    public function storeUpgradeSafety(Request $request)
    {
        $roadProject = new RoadUpgradeSafety;

        $roadProject->user_id = Auth::user()->id;
        // $roadProject->user_id = 470;
        $roadProject->province_id = $request->input('province-id') ?? null;
        $province_fa = \App\Models\Province::find($request->input('province-id'));
        $roadProject->province_fa = $province_fa->name_fa;
        if ($request->input('cities-id')) {
            $roadProject->cities_id = json_decode($request->input('cities-id')) ?? null;
            $city = array();
            foreach (json_decode($request->input('cities-id')) as $city_id => $percent) {
                $x = \App\Models\City::find($city_id);
                $city[] = $x->name_fa;
            }
            $roadProject->city_1_fa = $city[0] ?? null;
            $roadProject->city_2_fa = $city[1] ?? null;
            $roadProject->city_3_fa = $city[2] ?? null;
        }
        $roadProject->axis_name = $request->input('axis-name') ?? null;
        $roadProject->axis_type = $request->input('axis-type') ?? null;
        if ($request->input('axis-type')) {
            switch ($request->input('axis-type')) {
                case 1:
                    $roadProject->axis_type_fa = 'شریانی';
                break;
                case 2:
                    $roadProject->axis_type_fa = 'اصلی';
                break;
                case 3:
                    $roadProject->axis_type_fa = 'فرعی';
                break;
                case 4:
                    $roadProject->axis_type_fa = 'روستایی';
                break;
            }
        }
        $roadProject->project_name = $request->input('project-name') ?? null;
        $roadProject->contractor_name = $request->input('contractor-name') ?? null;
        $roadProject->consultant_name = $request->input('consultant-name') ?? null;

        /*
        $accDate = $request->input('contract-date') ?? null;
        $accDateGregorian = Verta::getGregorian($accDate[0], $accDate[1], $accDate[2]);
        if (count($accDateGregorian) == 3) {
            $accDateGregorianSt = $accDateGregorian[0] . '-'
                . (($accDateGregorian[1] > 10) ? $accDateGregorian[1] : '0' . $accDateGregorian[1])
                . '-'
                . (($accDateGregorian[2] > 10) ? $accDateGregorian[2] : '0' . $accDateGregorian[2]);

            if (!strlen($accDateGregorianSt) == 10) {
                return response()->json([
                    'status' => 'succeed',
                    'message' => '',
                    'data' => -1
                ], 200);
            }
        } else {
            $accDateGregorianSt = null;
        }
        */
        $roadProject->contract_date = $request->input('contract-date') ?? null;
        $roadProject->contract_credit = $request->input('contract-credit') ?? null;
        if ($request->input('start-latlng')) {
            $roadProject->start_latlng = explode(',', $request->input('start-latlng')) ?? null;
        }
        if ($request->input('end-latlng')) {
            $roadProject->end_latlng = explode(',', $request->input('end-latlng')) ?? null;
        }

        $roadProject->save();

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

    public function updateUpgradeSafety(Request $request, $id)
    {
        $roadProject = RoadUpgradeSafety::find($id);

        // $roadProject->projectHistories()->create([
        //     'user_id' => 470,
        //     'previous_axis_name' => $roadProject->axis_name,
        //     'previous_axis_type' => $roadProject->axis_type,
        //     'previous_project_name' => $roadProject->project_name,
        //     'previous_cities_id' => ($roadProject->cities_id) ? json_encode($roadProject->cities_id) : null,
        //     'previous_contractor_name' => $roadProject->contractor_name,
        //     'previous_consultant_name' => $roadProject->consultant_name,
        //     'previous_contract_date' => $roadProject->contract_date,
        //     'previous_contract_credit' => $roadProject->contract_credit,
        //     'previous_start_latlng' => $roadProject->start_latlng,
        //     'previous_end_latlng' => $roadProject->end_latlng,
        //     'previous_submited_at' => $roadProject->submited_at,
        //     'previous_last_updated_at' => $roadProject->last_updated_at,
        //     'previous_project_distance' => $roadProject->project_distance,
        //     'previous_project_distance_update' => $roadProject->project_distance_update,
        //     'previous_contractor_credit' => $roadProject->contractor_credit,
        //     'previous_physical_progress' => $roadProject->physical_progress,
        //     'previous_description' => $roadProject->description,
        //     'previous_status' => $roadProject->status,
        //     'previous_project_status' => $roadProject->project_status
        // ]);

        $roadProject->province_id = $request->input('province-id') ?? $roadProject->province_id;
        $province_fa = \App\Models\Province::find($request->input('province-id'));
        $roadProject->province_fa = $province_fa->name_fa;
        if ($request->input('cities-id')) {
            $roadProject->cities_id = json_decode($request->input('cities-id')) ?? null;
            $city = array();
            foreach (json_decode($request->input('cities-id')) as $city_id => $percent) {
                $x = \App\Models\City::find($city_id);
                $city[] = $x->name_fa;
            }
            $roadProject->city_1_fa = $city[0] ?? null;
            $roadProject->city_2_fa = $city[1] ?? null;
            $roadProject->city_3_fa = $city[2] ?? null;
        }
        $roadProject->axis_name = $request->input('axis-name') ?? null;
        $roadProject->axis_type = $request->input('axis-type') ?? null;
        if ($request->input('axis-type')) {
            switch ($request->input('axis-type')) {
                case 1:
                    $roadProject->axis_type_fa = 'شریانی';
                break;
                case 2:
                    $roadProject->axis_type_fa = 'اصلی';
                break;
                case 3:
                    $roadProject->axis_type_fa = 'فرعی';
                break;
                case 4:
                    $roadProject->axis_type_fa = 'روستایی';
                break;
            }
        }
        $roadProject->project_name = $request->input('project-name') ?? $roadProject->project_name;
        $roadProject->contractor_name = $request->input('contractor-name') ?? $roadProject->contractor_name;
        $roadProject->consultant_name = $request->input('consultant-name') ?? $roadProject->consultant_name;
       
        $accDate = $request->input('contract-date') ?? $roadProject->contract_date;
        $accDateGregorian = Verta::getGregorian($accDate[0], $accDate[1], $accDate[2]);
        // if (count($accDateGregorian) == 3) {
        //     $accDateGregorianSt = $accDateGregorian[0] . '-'
        //         . (($accDateGregorian[1] > 10) ? $accDateGregorian[1] : '0' . $accDateGregorian[1])
        //         . '-'
        //         . (($accDateGregorian[2] > 10) ? $accDateGregorian[2] : '0' . $accDateGregorian[2]);

        //     if (!strlen($accDateGregorianSt) == 10) {
        //         return response()->json([
        //             'status' => 'succeed',
        //             'message' => '',
        //             'data' => -1
        //         ], 200);
        //     }
        // } else {
        //     $accDateGregorianSt = null;
        // }
        
        $roadProject->contract_date = $request->input('contract-date') ?? $roadProject->contract_date;
        $roadProject->contract_credit = $request->input('contract-credit') ?? $roadProject->contract_credit;
        if ($request->input('start-latlng')) {
            $roadProject->start_latlng = explode(',', $request->input('start-latlng')) ?? $roadProject->start_latlng;
        }
        if ($request->input('end-latlng')) {
            $roadProject->end_latlng = explode(',', $request->input('end-latlng')) ?? $roadProject->end_latlng;
        }

        $roadProject->save();

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

    public function getUpgradeSafetyDistance($id)
    {
        $roadProject = RoadUpgradeSafety::find($id);

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

    public function updateUpgradeSafetyDistance(Request $request, $id)
    {
        $roadProject = RoadUpgradeSafety::find($id);

        if ($request->input('project-distance')) {
            $roadProject->project_distance = json_decode($request->input('project-distance')) ?? $roadProject->project_distance;
        }
        $roadProject->project_description = ($request->input('project-description')) ? $request->input('project-description') : null;
        $roadProject->status = 1;

        $roadProject->save();

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

    public function submitUpgradeSafetyDistance($id)
    {
        $roadProject = RoadUpgradeSafety::find($id);

        $roadProject->status = 1;

        $roadProject->save();

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

    public function submitUpgradeSafety($id)
    {
        $roadProject = RoadUpgradeSafety::find($id);

        $roadProject->status = 2;
        $roadProject->submited_at = Carbon::now();
        $roadProject->submited_at_fa = verta(Carbon::now())->format('Y/n/j - H:i');

        $roadProject->save();

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => [
                'redirect' => 'https://rms.rmto.ir/road-upgrade-safety/showonmap?uid=' . $roadProject->id
            ]
        ], 200);
    }

    public function destroyUpgradeSafety($id)
    {
        $roadProject = RoadUpgradeSafety::find($id);
        $roadProjectHistory = \App\Models\RoadUpgradeSafetyHistory::where('project_id', $id)->get();
        foreach ($roadProjectHistory as $value) {
            $x = \App\Models\ProjectFile::where('project_fileable_id', $value->id)
                                        ->where('project_fileable_type', 'App\Models\RoadUpgradeSafetyHistory')
                                        ->get('path');
            \App\Models\ProjectFile::where('project_fileable_id', $value->id)
                                        ->where('project_fileable_type', 'App\Models\RoadUpgradeSafetyHistory')
                                        ->delete();
            if (isset($x) and count($x) > 0) {
                \Storage::delete($x[0]->path);
            }
            $value->delete();
        }
        $roadProject->delete();

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

    public function getUpgradeSafety($id)
    {
        $roadProject = RoadUpgradeSafety::find($id);
        $roadProjectHistories = $roadProject->projectHistories;

        $roadProjectHistoriesFiles = [];
        $imagesIndex = 0;

        foreach ($roadProjectHistories as $key => $roadProjectHistory) {
            foreach ($roadProjectHistory->files as $keyPath => $file) {
                $roadProjectHistoriesFiles[$imagesIndex] = asset('storage' . substr($file->path, 6));
                $imagesIndex++;
            }
        }

        $cities = [];
        $citiesIndex = 0;

        foreach ($roadProject->cities_id as $cityKey => $value) {
            $getCity = \App\Models\City::find($cityKey);

            $cities[$citiesIndex] = [
                'id' => $getCity->id,
                'name' => $getCity->name_fa,
                'value' =>  $value
            ];

            $citiesIndex++;
        }

        $roadProjectArray = [
            'id' => $roadProject->id,
            'province' => [
                'id' => ($roadProject->province) ? $roadProject->province->id : null,
                'name' => ($roadProject->province) ? $roadProject->province->name_fa : '-',
                'lat_lng' => [
                    $roadProject->province->center_lat,
                    $roadProject->province->center_long
                ]
            ],
            'cities' => $cities,
            'axis_name' => ($roadProject->axis_name) ? $roadProject->axis_name : '-',
            'axis_type' => ($roadProject->axis_type) ? : 0,
            'project_name' => ($roadProject->project_name) ? $roadProject->project_name : '-',
            'contractor_name' => ($roadProject->contractor_name) ? $roadProject->contractor_name : '-',
            'consultant_name' => ($roadProject->consultant_name) ? $roadProject->consultant_name : '-',
            'contract_date' => ($roadProject->contract_date) ? $roadProject->contract_date : '-',
            'contract_credit' => ($roadProject->contract_credit) ? $roadProject->contract_credit : '-',
            'submited_at' => ($roadProject->submited_at) ?
                verta($roadProject->submited_at)->format('Y/n/j - H:i') : '-',
            'last_updated_at' => ($roadProject->last_updated_at) ?
                verta($roadProject->last_updated_at)->format('Y/n/j - H:i') : '-',
            'start_latlng' => $roadProject->start_latlng,
            'end_latlng' => $roadProject->end_latlng,
            'project_distance' => $roadProject->project_distance,
            'project_distance_update' => $roadProject->project_distance_update,
            'physical_progress' => $roadProject->physical_progress,
            // 'credit_progress' => ((($roadProject->contract_credit - $roadProject->contractor_credit)
                // / $roadProject->contract_credit) * 100),
            'images' => $roadProjectHistoriesFiles,
            'project_status' => $roadProject->project_status,
            'project_description' => $roadProject->project_description,
            'rate' => ($roadProject->rate)? $roadProject->rate:null,
            'rate_desc' => ($roadProject->rate_desc)? $roadProject->rate_desc:null
        ];

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

    public function getUpgradeSafetyDistanceUpdate($id)
    {
        $roadProject = RoadUpgradeSafety::find($id);

        $roadProjectArray = [
            'project_distance' => $roadProject->project_distance,
            'project_distance_update' => $roadProject->project_distance_update,
            'contractor_credit' => $roadProject->contractor_credit,
            'project_status' => $roadProject->project_status,
            'physical_progress' => $roadProject->physical_progress
        ];

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

    public function updateUpgradeSafetyDistanceUpdate(Request $request, $id)
    {
        $roadProject = RoadUpgradeSafety::find($id);
        $history_id = $roadProject->projectHistories()->create([
            'user_id' => Auth::user()->id,
            // 'user_id' => 470,
            'previous_project_distance_update' => json_decode($request->input('project-distance-update')),
            // 'previous_contractor_credit' => $request->input('contractor-credit'),
            'previous_project_status' => $request->input('project-status'),
            'previous_team_latlng' => $request->input('team-latlng'),
            'previous_stop_reason' => $request->input('stop-reason') ?? null,
            // 'previous_physical_progress' => $request->input('physical-progress'),
            'previous_status' => 0
        ])->id;

        if ($request->input('project-distance-update')) {
            $roadProject->project_distance_update = json_decode($request->input('project-distance-update')) ?? $roadProject->project_distance_update;
        }
        $roadProject->contractor_credit = $request->input('contractor-credit');
        $roadProject->project_status = $request->input('project-status');
        switch ($request->input('project-status')) {
            case 1:
                $roadProject->project_status_fa = "در دست برنامه ریزی اولیه";
            break;
            case 2:
                $roadProject->project_status_fa = "در دست مطالعه و تهیه اسناد مناقصه";
            break;
            case 3:
                $roadProject->project_status_fa = "در دست مناقصه";
            break;
            case 4:
                $roadProject->project_status_fa = "در حال تجهیز کارگاه";
            break;
            case 5:
                $roadProject->project_status_fa = "در حال اجرا/فعال";
            break;
            case 6:
                $roadProject->project_status_fa = "در حال اجرا/متوقف";
            break;
            case 7:
                $roadProject->project_status_fa = "در حال آماده سازی برای افتتاح";
            break;
            case 8:
                $roadProject->project_status_fa = "تکمیل و خاتمه یافته و بهره برداری شده";
            break;
        }
        $roadProject->physical_progress = $request->input('physical-progress');

        $roadProject->last_updated_at = Carbon::now();
        $roadProject->last_updated_at_fa = verta(Carbon::now())->format('Y/n/j - H:i');

        $roadProject->save();

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

    public function getUpgradeSafetyDistanceUpdateList($id)
    {
        $roadProject = RoadUpgradeSafety::find($id);
        $roadProjectHistories = $roadProject->projectHistories;

        $roadProjectHistoriesArray = [];

        foreach ($roadProjectHistories as $key => $roadProjectHistory) {
            $roadProjectHistoriesArray[$key] = [
                'id' => $roadProjectHistory->id,
                'previous_project_distance_update' => $roadProjectHistory->previous_project_distance_update,
                'previous_contractor_credit' => $roadProjectHistory->previous_contractor_credit,
                'previous_project_status' => $roadProjectHistory->previous_project_status,
                'previous_stop_reason' => $roadProjectHistory->previous_stop_reason,
                'previous_team_latlng' => $roadProjectHistory->previous_team_latlng,
                'previous_status' => $roadProjectHistory->previous_status,
                'updated_at' => (($roadProjectHistory->previous_status == 1) ? verta($roadProjectHistory->updated_at)->format('Y/m/d - H:i') : '-'),
                'updated_at_ge' => $roadProjectHistory->updated_at,
                'images' => $roadProjectHistory->files
            ];
        }

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => [
                'distance' => $roadProject->project_distance,
                'distance_update' => $roadProjectHistoriesArray
            ]
        ], 200);
    }

    public function storeUpgradeSafetyHistoryImage(Request $request)
    {
        $request->validate([
            'history-id' => 'required|integer|exists:road_upgrade_safety_histories,id',
            'image' => 'required|image',
            'name' => 'required|string'
        ]);
            
        $roadProjectHistory = \App\Models\RoadUpgradeSafetyHistory::find($request->input('history-id'));
        
        $roadProjectHistory->files()
            ->where('path', 'like', '%img8_' . $request->input('name') . '_%')
            ->delete();
        
        $files_path = $request->file('image')->storeAs(
            'public/road_upgrade_safety',
            'img8_' . $request->input('name') . '_' . $roadProjectHistory->id . '_' . time() . '_' . $request->file('image')->getClientOriginalName()
        );
        
        $roadProjectHistory->files()->create([
            'path' => $files_path
        ]);

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

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

        $roadProjectHistory = \App\Models\RoadUpgradeSafetyHistory::find($request->input('history-id'));

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

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

    public function submitUpgradeSafetyHistory($id)
    {
        $roadProjectHistory = \App\Models\RoadUpgradeSafetyHistory::find($id);

        $roadProjectHistory->previous_status = 1;

        $roadProjectHistory->save();

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

    public function showUpgradeSafetyMap()
    {
        return view('rmto-preview.pages.road-upgrade-safety-map');
    }

    public function getUpgradeSafetyProvinceStat(Request $request)
    {
        $request->validate([
            'province-id' => 'integer|exists:provinces,id',
            'end-date' => 'date_format:Y-m-d',
            'axis-types' => 'string'
        ]);

        if ($request->input('end-date')) {
            $endDate = date($request->input('end-date') . ' 23:59:59');
        } else {
            $endDate = date('Y-m-d H:i:s');
        }

        if ($request->input('axis-types')) {
            $axisTypes = explode(',', $request->input('axis-types'));
        } else {
            $axisTypes = [1, 2, 3, 4];
        }

        $city_id = $request->input('city-id') ?? null;
        $province_id = $request->input('province-id') ?? null;
        $roadProjects = RoadUpgradeSafety::
                                when(!empty($axisTypes), function ($query) use ($axisTypes) {
                                    return $query->whereIn('axis_type', $axisTypes);
                                })
                                ->when(!empty($province_id), function ($query) use ($province_id) {
                                    return $query->where('province_id', $province_id);
                                })
                                ->when(!empty($city_id), function ($query) use ($city_id) {
                                    return $query->where('cities_id', 'like', '%"'.$city_id.'":%');
                                })
                                ->with(['projectHistories' => function ($query) use ($endDate) {
                                    $query->whereDate('updated_at', '<=', $endDate);
                                }])
                                ->get();
        $roadProjects_count = $roadProjects->count();

        $roadProjectsArray = [];
        $lastArraySum = [
            0 => 0
        ];

        foreach ($roadProjects as $projectKey => $roadProject) {
            if (!$roadProject->projectHistories->isEmpty()) {
                $lastProjectHistory = $roadProject->projectHistories->last();

                foreach ($roadProject->cities_id as $cityKey => $value) {
                    if (isset($roadProjectsArray[$cityKey])) {
                        $roadProjectsArray[$cityKey]['projectsCount'] += 1;
                        foreach ($lastProjectHistory->previous_project_distance_update as $keyUpdate => $distance) {
                            $roadProjectsArray[$cityKey]['projectDistance'][$keyUpdate][0] += (($distance[0] != "" && $distance[0] >= 0) ? (float)$distance[0] : 0);
                            // $roadProjectsArray[$cityKey]['projectDistance'][$keyUpdate][1] += (($distance[1] != "" && $distance[1] >= 0) ? (float) $distance[1] : 0);
                        }
                    } else {
                        $roadProjectsArray[$cityKey]['projectsCount'] = 1;
                        $roadProjectsArray[$cityKey]['projectDistance'] = [
                            1 => [
                                0, 0
                            ],
                            2 => [
                                0, 0
                            ],
                            3 => [
                                0, 0
                            ],
                            4 => [
                                0, 0
                            ],
                            5 => [
                                0, 0
                            ],
                            6 => [
                                0, 0
                            ],
                            7 => [
                                0, 0
                            ],
                            8 => [
                                0, 0
                            ],
                            9 => [
                                0, 0
                            ]
                        ];

                        foreach ($lastProjectHistory->previous_project_distance_update as $keyUpdate => $distance) {
                            $roadProjectsArray[$cityKey]['projectDistance'][$keyUpdate][0] = (($distance[0] != "" && $distance[0] >= 0) ? (float)$distance[0] : 0);
                            $roadProjectsArray[$cityKey]['projectDistance'][$keyUpdate][1] = (($distance[1] != "" && $distance[1] >= 0) ? (float)$distance[1] : 0);
                        }
                    }
                }
            }
        }

        $lastArray = [];
        $arrayIndex = 0;

        foreach ($roadProjectsArray as $cityKey => $value) {
            $getCity = \App\Models\City::find($cityKey);
            $getProvince = \App\Models\Province::find($getCity->province_id);
            $lastArray[$arrayIndex] = $value;
            $lastArray[$arrayIndex]['cityName'] = $getCity->name_fa;
            $lastArray[$arrayIndex]['cityId'] = $getCity->id;
            $lastArray[$arrayIndex]['proviceName'] = $getProvince->name_fa;
            $lastArray[$arrayIndex]['proviceId'] = $getProvince->id;
            $lastArraySum[0] += $lastArray[$arrayIndex]['projectsCount'];
            $arrayIndex++;
        }


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

    public function getRoadMaintenanceReportPage()
    {
        return view('rmto-preview.pages.road-maintenance-report');
    }
    public function indexPoints()
    {
        $roadProjects = RoadUpgradeSafety::where('status', 2)->get();
        $roadProjectArray = [];

        foreach ($roadProjects as $key => $roadProject) {
            $roadProjectHistories = $roadProject->projectHistories;

            $roadProjectHistoriesFiles = [];
            $imagesIndex = 0;

            foreach ($roadProjectHistories as $key => $roadProjectHistory) {
                foreach ($roadProjectHistory->files as $keyPath => $file) {
                    $roadProjectHistoriesFiles[$imagesIndex] = asset('storage' . substr($file->path, 6));
                    $imagesIndex++;
                }
            }

            $cities = [];
            $citiesIndex = 0;

            foreach ($roadProject->cities_id as $cityKey => $value) {
                $getCity = \App\Models\City::find($cityKey);

                $cities[$citiesIndex] = [
                    'id' => $getCity->id,
                    'name' => $getCity->name_fa,
                    'value' =>  $value
                ];

                $citiesIndex++;
            }

            $roadProjectArray[$key] = [
                'id' => $roadProject->id,
                'province' => [
                    'id' => ($roadProject->province) ? $roadProject->province->id : null,
                    'name' => ($roadProject->province) ? $roadProject->province->name_fa : '-',
                    'lat_lng' => [
                        $roadProject->province->center_lat,
                        $roadProject->province->center_long
                    ]
                ],
                'cities' => $cities,
                'axis_name' => ($roadProject->axis_name) ? $roadProject->axis_name : '-',
                'axis_type' => ($roadProject->axis_type) ? : 0,
                'project_name' => ($roadProject->project_name) ? $roadProject->project_name : '-',
                'contractor_name' => ($roadProject->contractor_name) ? $roadProject->contractor_name : '-',
                'consultant_name' => ($roadProject->consultant_name) ? $roadProject->consultant_name : '-',
                'contract_date' => ($roadProject->contract_date) ?
                    verta($roadProject->contract_date)->format('Y/n/j') : '-',
                'contract_credit' => ($roadProject->contract_credit) ? $roadProject->contract_credit : '-',
                'submited_at' => ($roadProject->submited_at) ?
                    verta($roadProject->submited_at)->format('Y/n/j - H:i') : '-',
                'last_updated_at' => ($roadProject->last_updated_at) ?
                    verta($roadProject->last_updated_at)->format('Y/n/j - H:i') : '-',
                'start_latlng' => $roadProject->start_latlng,
                'end_latlng' => $roadProject->end_latlng,
                'project_distance' => $roadProject->project_distance,
                'project_distance_update' => $roadProject->project_distance_update,
                'physical_progress' => $roadProject->physical_progress,
                // 'credit_progress' => ((($roadProject->contract_credit - $roadProject->contractor_credit)
                //     / $roadProject->contract_credit) * 100),
                'images' => $roadProjectHistoriesFiles,
                'project_status' => $roadProject->project_status
            ];
        }

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $roadProjectArray
        ], 200);
    }
    public function submitRoadUpgradeSafetyRate(Request $request)
    {
        $request->validate([
            'id' => 'required',
            'rate' => 'required'
        ]);
        // $roadProject->province_id = $request->input('province-id') ?? null;
        $data = RoadUpgradeSafety::find($request->input('id'));
        $data->rate = $request->input('rate');
        $data->rate_desc = $request->input('rate_desc') ?? null;
        $data->save();
        return response()->json([
            'status' => 'succeed',
            'message' => ''
        ], 200);
    }
}
