<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\RoadMaintenanceProject;
use Illuminate\Support\Facades\Auth;

class RoadMaintenanceProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $projects = RoadMaintenanceProject::all();
        $projectsArray = [];

        foreach ($projects As $key => $project) {
            $projectsArray[$key] = [
                'id' => $project->id,
                'axis_name' => ($project->axis_name) ? $project->axis_name : '-',
                'axis_type' => ($project->axis_type) ? : 0,
                'project_name' => ($project->project_name) ? $project->project_name : '-',
                'province' => [
                    'id' => ($project->province) ? $project->province->id : null,
                    'name' => ($project->province) ? $project->province->name_fa : '-'
                ],
                'city' => [
                    'id' => ($project->city) ? $project->city->id : null,
                    'name' => ($project->city) ? $project->city->name_fa : '-'
                ],
                'contractor_name' => ($project->contractor_name) ? $project->contractor_name : '-',
                'consultant_name' => ($project->consultant_name) ? $project->consultant_name : '-',
                'contract_date' => ($project->contract_date) ? 
                    verta(date('Y-m-d', $project->contract_date))->format('Y/n/j') : '-',
                'contract_credit' => ($project->contract_credit) ? $project->contract_credit : '-',
            ];
        }

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

    public function indexStatus() {
        $projects = RoadMaintenanceProject::all();

        $projectsArray = [];

        foreach ($projects As $key => $project) {
            $projectsArray[$key] = [
                'id' => $project->id,
                'axis_name' => ($project->axis_name) ? $project->axis_name : '-',
                'axis_type' => ($project->axis_type) ? : 0,
                'project_name' => ($project->project_name) ? $project->project_name : '-',
                'province' => [
                    'id' => ($project->province) ? $project->province->id : null,
                    'name' => ($project->province) ? $project->province->name_fa : '-'
                ],
                'city' => [
                    'id' => ($project->city) ? $project->city->id : null,
                    'name' => ($project->city) ? $project->city->name_fa : '-'
                ],
                'contractor_name' => ($project->contractor_name) ? $project->contractor_name : '-',
                'consultant_name' => ($project->consultant_name) ? $project->consultant_name : '-',
                'project_distance' => ($project->project_distance) ? $project->project_distance : null,
                'project_distance_update' => ($project->project_distance_update) ? $project->project_distance_update : null,
                'contract_date' => ($project->contract_date) ? 
                    verta(date('Y-m-d', $project->contract_date))->format('Y/n/j') : '-',
                'contract_credit' => ($project->contract_credit) ? $project->contract_credit : '-',
                'contractor_credit' => ($project->contractor_credit) ? $project->contractor_credit : '-',
                'physical_progress' => ($project->physical_progress) ? $project->physical_progress : '-',
                'start_latlng' => ($project->start_latlng) ? $project->start_latlng : null,
                'end_latlng' => ($project->end_latlng) ? $project->end_latlng : null,
                'description' => ($project->description) ? $project->description : '-',
                'updated_at' => verta($project->updated_at)->format('Y/n/j - H:i')
            ];
        }

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

    public function indexPoints() {
        $roadMaintenanceProjects = RoadMaintenanceProject::where('status', 2)->where('last_updated_at', '<>', '')->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
        //     ];
        // }


        $roadConstructionProjects = \App\Models\RoadConstructionRural::where('status', 2)->where('last_updated_at', '<>', '')->get();
        $roadConstructionRuralProjectArray = [];

        // 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++;
        //     }

        //     $roadConstructionRuralProjectArray[$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
        //     ];
        // }

        $roadDangerProjects = \App\Models\RoadDangerPrevention::where('status', 2)->where('last_updated_at', '<>', '')->get();
        $roadDangerPreventionProjectArray = [];

        // 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++;
        //     }

        //     $roadDangerPreventionProjectArray[$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
        //     ];
        // }
        $roadTechnicalProjects = \App\Models\RoadTechnicalBuilding::where('status', 2)->where('last_updated_at', '<>', '')->get();
        $roadTechnicalBuildingProjectArray = [];

        // 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++;
        //     }

        //     $roadTechnicalBuildingProjectArray[$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
        //     ];
        // }
        $roadTollhouseProjects = \App\Models\RoadTollhouseManagement::where('status', 2)->where('last_updated_at', '<>', '')->get();
        $roadTollhouseManagementProjectArray = [];

        // 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++;
        //     }

        //     $roadTollhouseManagementProjectArray[$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
        //     ];
        // }
        $roadUpgradeProjects = \App\Models\RoadUpgradeSafety::where('status', 2)->where('last_updated_at', '<>', '')->get();
        $roadUpgradeSafetyProjectArray = [];

        // 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++;
        //     }

        //     $roadUpgradeSafetyProjectArray[$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,
            'RoadConstructionRural' => $roadConstructionProjects,
            'RoadDangerPrevention' => $roadDangerProjects,
            'RoadTollhouseManagement' => $roadTollhouseProjects,
            'RoadUpgradeSafety' => $roadUpgradeProjects,
            'RoadTechnicalBuilding' => $roadTechnicalProjects,
            'RoadMaintenanceProject' => $roadMaintenanceProjects
        ], 200);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('rmto-preview.pages.road-maintenance');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function createNew()
    {
        return view('rmto-preview.pages.road-maintenance-new');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $roadProject = new RoadMaintenanceProject;

        $roadProject->axis_name = $request->input('axis-name') ?? null;
        $roadProject->axis_type = $request->input('axis-type') ?? null;
        $roadProject->project_name = $request->input('project-name') ?? null;
        $roadProject->province_id = $request->input('province-id') ?? null;
        $roadProject->city_id = $request->input('city-id') ?? null;
        $roadProject->contractor_name = $request->input('contractor-name') ?? null;
        $roadProject->project_distance = json_decode($request->input('project-distance')) ?? null;
        if ($request->input('contract-date') && $request->input('contract-date') > 0) {
            $roadProject->contract_date = $request->input('contract-date') ?? null;
        }
        $roadProject->contract_credit = $request->input('contract-credit') ?? null;
        $roadProject->contractor_credit = $request->input('contractor-credit') ?? null;
        $roadProject->physical_progress = $request->input('physical-progress') ?? 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->description = $request->input('description') ?? null;

        // PUBLIC URL
        // $user = \App\Models\User::find(470);
        $roadMaintenance = $request->user()->roadMaintenanceProjects()->save($roadProject);
        // $roadMaintenance = $user->roadMaintenanceProjects()->save($roadProject);
        
        /*$file_index = 0;
        $files_path = [];
        while (true) {
            if ($request['files_' . $file_index]) {
                $files_path[$file_index]['path'] = $request->file('files_' . $file_index)
                    ->store('public/road_maintenance_projects');
                $file_index++;
            } else {
                break;
            }
        }

        if ($file_index > 0) {
            $roadMaintenance->files()->createMany($files_path);
        }*/

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $project = RoadMaintenanceProject::where('id', $id)->with('province')->get();

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $roadProject = RoadMaintenanceProject::find($id);

        /*$file_index = 0;
        $files_path = [];
        while (true) {
            if ($request['files_' . $file_index]) {
                $files_path[$file_index]['path'] = $request->file('files_' . $file_index)
                    ->store('public/road_maintenance_projects');
                $file_index++;
            } else {
                break;
            }
        }*/

        $roadProject->projectHistories()->create([
            // PUBLIC URL
            'user_id' => $request->user()->id,
            'previous_axis_name' => $roadProject->axis_name,
            'previous_axis_type' => $roadProject->axis_type,
            'previous_project_name' => $roadProject->project_name,
            'previous_contractor_name' => $roadProject->contractor_name,
            'previous_consultant_name' => $roadProject->consultant_name,
            'previous_project_distance' => ($roadProject->project_distance) ? json_encode($roadProject->project_distance) : null,
            'previous_project_distance_update' => ($roadProject->project_distance_update) ? json_encode($roadProject->project_distance_update) : null,
            'previous_contract_date' => $roadProject->contract_date,
            'previous_contract_credit' => $roadProject->contract_credit,
            'previous_contractor_credit' => $roadProject->contractor_credit,
            'previous_physical_progress' => $roadProject->physical_progress,
            'previous_start_latlng' => $roadProject->start_latlng,
            'previous_end_latlng '=> $roadProject->end_latlng,
            'previous_description' => $roadProject->description,
            //'new_files' => json_encode($files_path)
        ]);

        $roadProject->axis_name = $request->input('axis-name') ?? $roadProject->axis_name;
        $roadProject->axis_type = $request->input('axis-type') ?? $roadProject->axis_type;
        $roadProject->project_name = $request->input('project-name') ?? $roadProject->project_name;
        $roadProject->province_id = $request->input('province-id') ?? $roadProject->province_id;
        $roadProject->city_id = $request->input('city-id') ?? $roadProject->city_id;
        $roadProject->contractor_name = $request->input('contractor-name') ?? $roadProject->contractor_name;
        $roadProject->consultant_name = $request->input('consultant-name') ?? $roadProject->consultant_name;
        if ($request->input('project-distance')) {
            $roadProject->project_distance = json_decode($request->input('project-distance')) ?? null;
        }
        if ($request->input('contract-date') && $request->input('contract-date') > 0) {
            $roadProject->contract_date = $request->input('contract-date') ?? $roadProject->contract_date;
        }
        $roadProject->contract_credit = $request->input('contract-credit') ?? $roadProject->contract_credit;
        $roadProject->contractor_credit = $request->input('contractor-credit') ?? $roadProject->contractor_credit;
        $roadProject->physical_progress = $request->input('physical-progress') ?? $roadProject->physical_progress;
        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->description = $request->input('description') ?? $roadProject->description;

        $roadProject->save();

        /*if ($file_index > 0) {
            $roadMaintenance->files()->createMany($files_path);
        }*/

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function updateStatus(Request $request, $id)
    {
        $roadProject = RoadMaintenanceProject::find($id);

        $file_index = 0;
        $files_path = [];
        while (true) {
            if ($request['files_' . $file_index]) {
                $files_path[$file_index]['path'] = $request->file('files_' . $file_index)
                    ->store('public/road_maintenance_projects');
                $file_index++;
            } else {
                break;
            }
        }

        $roadProject->projectHistories()->create([
            'user_id' => $request->user()->id,
            'previous_axis_name' => $roadProject->axis_name,
            'previous_axis_type' => $roadProject->axis_type,
            'previous_project_name' => $roadProject->project_name,
            'previous_contractor_name' => $roadProject->contractor_name,
            'previous_consultant_name' => $roadProject->consultant_name,
            'previous_project_distance' => ($roadProject->project_distance) ? json_encode($roadProject->project_distance) : null,
            'previous_project_distance_update' => ($roadProject->project_distance_update) ? json_encode($roadProject->project_distance_update) : null,
            'previous_contract_date' => $roadProject->contract_date,
            'previous_contract_credit' => $roadProject->contract_credit,
            'previous_contractor_credit' => $roadProject->contractor_credit,
            'previous_physical_progress' => $roadProject->physical_progress,
            'previous_start_latlng' => $roadProject->start_latlng,
            'previous_end_latlng '=> $roadProject->end_latlng,
            'previous_description' => $roadProject->description,
            'new_files' => json_encode($files_path)
        ]);

        $roadProject->axis_name = $request->input('axis-name') ?? $roadProject->axis_name;
        $roadProject->axis_type = $request->input('axis-type') ?? $roadProject->axis_type;
        $roadProject->project_name = $request->input('project-name') ?? $roadProject->project_name;
        $roadProject->province_id = $request->input('province-id') ?? $roadProject->province_id;
        $roadProject->city_id = $request->input('city-id') ?? $roadProject->city_id;
        $roadProject->contractor_name = $request->input('contractor-name') ?? $roadProject->contractor_name;
        $roadProject->consultant_name = $request->input('consultant-name') ?? $roadProject->consultant_name;
        if ($request->input('project-distance')) {
            $roadProject->project_distance_update = json_decode($request->input('project-distance')) ?? $roadProject->project_distance_update;
        }
        if ($request->input('contract-date') && $request->input('contract-date') > 0) {
            $roadProject->contract_date = $request->input('contract-date') ?? $roadProject->contract_date;
        }
        $roadProject->contract_credit = $request->input('contract-credit') ?? $roadProject->contract_credit;
        $roadProject->contractor_credit = $request->input('contractor-credit') ?? $roadProject->contractor_credit;
        $roadProject->physical_progress = $request->input('physical-progress') ?? $roadProject->physical_progress;
        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->description = $request->input('description') ?? $roadProject->description;

        $roadProject->save();

        if ($file_index > 0) {
            $roadProject->files()->createMany($files_path);
        }

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * Show the form for status projects.
     *
     * @return \Illuminate\Http\Response
     */
    public function getLastStatus()
    {
        return view('rmto-preview.pages.road-maintenance-status');
    }

    public function getMaintenanceProjectProvinceStat(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];
        }

        // if (Auth::user()->username == 'drdanesh' || Auth::user()->username == 'witel') {
        //     if ($request->input('province-id')) {
        //         $roadProjects = RoadMaintenanceProject::where('province_id', $request->input('province-id'))
        //             ->whereIn('axis_type', $axisTypes)
        //             ->with(['projectHistories' => function ($query) use ($endDate) {
        //                 $query->whereDate('updated_at', '<=', $endDate);
        //             }])
        //             ->get();
        //     } else {
        //         $roadProjects = RoadMaintenanceProject::whereIn('axis_type', $axisTypes)
        //             ->with(['projectHistories' => function ($query) use ($endDate) {
        //                 $query->whereDate('updated_at', '<=', $endDate);
        //             }])
        //             ->get();
        //     }
        // } else {
        //     $roadProjects = RoadMaintenanceProject::where('province_id', Auth::user()->province_id)
        //         ->whereIn('axis_type', $axisTypes)
        //         ->with(['projectHistories' => function ($query) use ($endDate) {
        //             $query->whereDate('updated_at', '<=', $endDate);
        //         }])
        //         ->get();
        // }

        $city_id = $request->input('city-id') ?? null;
        $province_id = $request->input('province-id') ?? null;
        $roadProjects = RoadMaintenanceProject::
                                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,
            1 => 0,
            2 => 0,
            3 => 0,
            4 => 0,
            5 => 0,
            6 => 0,
            7 => 0,
            8 => 0,
            9 => 0,
            10 => 0,
            11 => 0,
            12 => 0,
            13 => 0,
            14 => 0,
            15 => 0,
            16 => 0,
            17 => 0,
            18 => 0,
            19 => 0,
            20 => 0,
            21 => 0,
            22 => 0,
            23 => 0,
            24 => 0,
            25 => 0,
            26 => 0,
            27 => 0,
            28 => 0,
            29 => 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;
                        $roadProjectsArray[$cityKey]['contractCredit'] += (($roadProject->contract_credit * $value) / 100);
                        $roadProjectsArray[$cityKey]['contractorCredit'] += (($lastProjectHistory->previous_contractor_credit * $value) / 100);
                        $roadProjectsArray[$cityKey]['physicalProgress'] += $lastProjectHistory->previous_physical_progress;
                
                        foreach ($lastProjectHistory->previous_project_distance_update as $keyUpdate => $distance) {
                            if ($keyUpdate < 12) {
                                $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);
                                $roadProjectsArray[$cityKey]['projectDistance'][$keyUpdate][2] += (($distance[2] != "" && $distance[2] >= 0) ? (float)$distance[1] : 0);
                            } elseif ($keyUpdate == 12) {
                                $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);
                                $roadProjectsArray[$cityKey]['projectDistance'][$keyUpdate][2] += (($distance[2] != "" && $distance[2] >= 0) ? (float)$distance[2] : 0);
                                $roadProjectsArray[$cityKey]['projectDistance'][$keyUpdate][3] += (($distance[3] != "" && $distance[3] >= 0) ? (float)$distance[2] : 0);
                            } elseif ($keyUpdate == 13) {
                                $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[0] : 0);
                            }
                        }
                    } else {
                        $roadProjectsArray[$cityKey]['projectsCount'] = 1;
                        $roadProjectsArray[$cityKey]['contractCredit'] = (($roadProject->contract_credit * $value) / 100);
                        $roadProjectsArray[$cityKey]['contractorCredit'] = (($lastProjectHistory->previous_contractor_credit * $value) / 100);
                        $roadProjectsArray[$cityKey]['physicalProgress'] = $lastProjectHistory->previous_physical_progress;
                        $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
                            ],
                            10 => [
                                0, 0
                            ],
                            11 => [
                                0, 0
                            ],
                            12 => [
                                0, 0, 0
                            ],
                            13 => [
                                0
                            ]
                        ];

                        foreach ($lastProjectHistory->previous_project_distance_update as $keyUpdate => $distance) {
                            if ($keyUpdate < 12) {
                                $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);
                                $roadProjectsArray[$cityKey]['projectDistance'][$keyUpdate][2] = (($distance[2] != "" && $distance[2] >= 0) ? (float)$distance[2] : 0);
                            } elseif ($keyUpdate == 12) {
                                $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);
                                $roadProjectsArray[$cityKey]['projectDistance'][$keyUpdate][2] = (($distance[2] != "" && $distance[2] >= 0) ? (float)$distance[2] : 0);
                                $roadProjectsArray[$cityKey]['projectDistance'][$keyUpdate][3] = (($distance[3] != "" && $distance[3] >= 0) ? (float)$distance[3] : 0);
                            } elseif ($keyUpdate == 13) {
                                $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);

            $lastArray[$arrayIndex] = $value;
            $lastArray[$arrayIndex]['cityName'] = $getCity->name_fa;
            $lastArray[$arrayIndex]['physicalProgress'] = (int)($lastArray[$arrayIndex]['physicalProgress'] / $lastArray[$arrayIndex]['projectsCount']);

            $lastArraySum[0] += $lastArray[$arrayIndex]['projectsCount'];
            $lastArraySum[1] += $lastArray[$arrayIndex]['contractCredit'];
            $lastArraySum[2] += $lastArray[$arrayIndex]['contractorCredit'];
            $lastArraySum[3] += $lastArray[$arrayIndex]['physicalProgress'];
            $lastArraySum[4] += $lastArray[$arrayIndex]['projectDistance'][13][0];
            $lastArraySum[5] += $lastArray[$arrayIndex]['projectDistance'][12][0];
            $lastArraySum[6] += $lastArray[$arrayIndex]['projectDistance'][12][1];
            $lastArraySum[7] += $lastArray[$arrayIndex]['projectDistance'][12][2];
            $lastArraySum[8] += $lastArray[$arrayIndex]['projectDistance'][1][0];
            $lastArraySum[9] += $lastArray[$arrayIndex]['projectDistance'][1][1];
            $lastArraySum[10] += $lastArray[$arrayIndex]['projectDistance'][2][0];
            $lastArraySum[11] += $lastArray[$arrayIndex]['projectDistance'][2][1];
            $lastArraySum[12] += $lastArray[$arrayIndex]['projectDistance'][3][0];
            $lastArraySum[13] += $lastArray[$arrayIndex]['projectDistance'][3][1];
            $lastArraySum[14] += $lastArray[$arrayIndex]['projectDistance'][4][0];
            $lastArraySum[15] += $lastArray[$arrayIndex]['projectDistance'][4][1];
            $lastArraySum[16] += $lastArray[$arrayIndex]['projectDistance'][5][0];
            $lastArraySum[17] += $lastArray[$arrayIndex]['projectDistance'][5][1];
            $lastArraySum[18] += $lastArray[$arrayIndex]['projectDistance'][6][0];
            $lastArraySum[19] += $lastArray[$arrayIndex]['projectDistance'][6][1];
            $lastArraySum[20] += $lastArray[$arrayIndex]['projectDistance'][7][0];
            $lastArraySum[21] += $lastArray[$arrayIndex]['projectDistance'][7][1];
            $lastArraySum[22] += $lastArray[$arrayIndex]['projectDistance'][8][0];
            $lastArraySum[23] += $lastArray[$arrayIndex]['projectDistance'][8][1];
            $lastArraySum[24] += $lastArray[$arrayIndex]['projectDistance'][9][0];
            $lastArraySum[25] += $lastArray[$arrayIndex]['projectDistance'][9][1];
            $lastArraySum[26] += $lastArray[$arrayIndex]['projectDistance'][10][0];
            $lastArraySum[27] += $lastArray[$arrayIndex]['projectDistance'][10][1];
            $lastArraySum[28] += $lastArray[$arrayIndex]['projectDistance'][11][0];
            $lastArraySum[29] += $lastArray[$arrayIndex]['projectDistance'][11][1];

            $arrayIndex++;
        }

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