<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\RoadUpgradeSafety;
use App\Models\RoadDangerPrevention;
use App\Models\RoadTechnicalBuilding;
use App\Models\RoadMaintenanceProject;
use App\Models\RoadTollhouseManagement;
use App\Models\RoadItemsProject;
use App\Models\RoadPatrol;
use App\Models\AccidentPoint;
use App\Models\DangerPoint;
use App\Models\Camp;
use App\Models\ContractSubItems;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Models\Province;
use App\Models\City;
use App\Models\RahdariPoint;
use App\Models\InfoItem;
use App\Models\RoadObserved;

class BiController extends Controller
{
    public function getSubtitleCounts(Request $request)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1054);
        }
        $subjectID = $request->subject_id;
        $dateFrom = $request->from_date;
        $dateTo = $request->to_date;
        $provinceID = $request->province_id;
        $cityID = $request->city_id;

        /// Number of Rahdari Projects
        $rahdariSum = ContractSubItems::when($provinceID, function ($query, $provinceID) {
            return $query->where('province_id', $provinceID);
        })
                                        ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                            return $query->whereBetween('contract_date_from_parent_contract', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                                        })
                                        ->when($cityID, function ($query, $cityID) {
                                            return $query->where('city_id', $cityID);
                                        })
                                        ->count();
        
        /// Number of Road items project
        $roadItemsProjectsCount = RoadItemsProject::when($provinceID, function ($query, $provinceID) {
            return $query->where('province_id', $provinceID);
        })
                                                    ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                                        return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                                                    })
                                                    ->when($cityID, function ($query, $cityID) {
                                                        return $query->where('city_id', $cityID);
                                                    })
                                                    ->count();
        
        /// Number of Road patrol projects
        $roadPatrolProjects = RoadPatrol::when($provinceID, function ($query, $provinceID) {
            return $query->where('province_id', $provinceID);
        })
                                                ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                                    return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                                                })
                                                ->when($cityID, function ($query, $cityID) {
                                                    return $query->where('city_id', $cityID);
                                                })
                                                ->count();

        /// Number of Road Observeds
        $roadObservedCount = RoadObserved::where('rms_status', '!=', 0)
                                            ->when($provinceID, function ($query, $provinceID) {
                                                return $query->where('rms_province_id', $provinceID);
                                            })
                                            ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                                return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                                            })
                                            ->when($cityID, function ($query, $cityID) {
                                                return $query->where('rms_city_id', $cityID);
                                            })
                                            
                                            ->count();

        // Number of Accident points in 1395
        $accidentPointsCount = AccidentPoint::count();

        // Number of Danger points in 1399
        $dangerPointCount = DangerPoint::when($provinceID, function ($query, $provinceID) {
            return $query->where('province_id', $provinceID);
        })
                                        ->when($cityID, function ($query, $cityID) {
                                            return $query->where('city_id', $cityID);
                                        })
                                        ->count();

        // Number of camp
        $campsCount = Camp::when($provinceID, function ($query, $provinceID) {
            return $query->where('province_id', $provinceID);
        })
                            ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                            })
                            ->when($cityID, function ($query, $cityID) {
                                return $query->where('cities_id', $cityID);
                            })
                            ->count();

        return response()->json([
            'message' => 'success',
            'data' =>  [
                'subjects' => [
                    [
                        'count' => $rahdariSum,
                        'action_id' => '1'
                    ],
                    [
                        'count' => $roadItemsProjectsCount,
                        'action_id' => '2'
                    ],
                    [
                        'count' => $roadPatrolProjects,
                        'action_id' => '3'
                    ],
                    [
                        'count' => $roadObservedCount,
                        'action_id' => '4'
                    ],
                    [
                        'count' => $accidentPointsCount,
                        'action_id' => '5'
                    ],
                    [
                        'count' => $dangerPointCount,
                        'action_id' => '6'
                    ],
                    [
                        'count' => $campsCount,
                        'action_id' => '7'
                    ]
                ],
            ]

        ]);
    }

    public function getDiagram(Request $request)
    {
        ini_set('memory_limit', '-1');
        $subjectID = $request->subject_id;
        $provinceID = $request->province_id;
        $dateFrom = $request->from_date;
        $dateTo = $request->to_date;
        
        $todayDate = Carbon::now()->format('Y-m-d');
        $provinces = Province::select('id', 'name_fa')->get();
        $cities = City::select('id', 'name_fa')
                        ->where("type_id", 1)
                        ->where('province_id', $provinceID)
                        ->get();
        $array = [];
        switch ($subjectID) {
            case 1:
                if (! $provinceID) {
                    $array = self::createArrayFromProvincesOrCities($provinces, $array);
                }

                if ($provinceID) {
                    $array = self::createArrayFromProvincesOrCities($cities, $array);
                }

                $data = DB::table('contract_subitems')
                ->where('progress_project', '!=', null)

                            ->select('province_id', 'province_fa', DB::raw('round(avg(progress_project), 1) as count, count(progress_project) as count_number'))
                            ->groupBy('province_id')
                            ->when($provinceID, function ($query, $provinceID) {
                                return $query->where('province_id', $provinceID)
                                    ->select('city_id', 'city_fa', DB::raw('round(avg(progress_project), 1) as count, count(progress_project) as count_number'))
                                    ->groupBy('city_id');
                            })
                            ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                return $query->whereBetween('contract_date_from_parent_contract', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                            })
                            ->get();
                $array = self::createDataArray($data, $array);
                $array_for_number = self::createDataArrayForCountNumber($data, $array);

                break;
            case 2:
                if (! $provinceID) {
                    $array = self::createArrayFromProvincesOrCities($provinces, $array);
                }

                if ($provinceID) {
                    $array = self::createArrayFromProvincesOrCities($cities, $array);
                }
                $data = DB::table('road_items_projects')
                            ->select('province_id', 'province_fa')
                            ->when($provinceID, function ($query, $provinceID) {
                                return $query->where('province_id', $provinceID)
                                    ->select('city_id', 'city_fa');
                            })
                            ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                            })
                            ->get();
                $dataAfter = [];
                if($provinceID) {
                    foreach ($data as $key => $value) {
                        $dataAfter[$value->city_id - 1]['city_fa'] = $value->city_id;
                        $dataAfter[$value->city_id - 1]['city_id'] = $value->city_id;
                        if(!isset($dataAfter[$value->city_id - 1]['count'])) $dataAfter[$value->city_id - 1]['count'] =0;
                        $dataAfter[$value->city_id - 1]['count']++;
                    }
                } else {
                    foreach ($data as $key => $value) {
                        $dataAfter[$value->province_id - 1]['province_fa'] = $value->province_fa;
                        $dataAfter[$value->province_id - 1]['province_id'] = $value->province_id;
                        if(!isset($dataAfter[$value->province_id - 1]['count'])) $dataAfter[$value->province_id - 1]['count'] =0;
                        $dataAfter[$value->province_id - 1]['count']++;
                    }

                }
                
                $array = self::createDataArray($dataAfter, $array);

                break;
            case 3:
                // if (! $provinceID) {
                //     $array = self::createArrayFromProvincesOrCities($provinces, $array);
                // }

                // if ($provinceID) {
                //     $array = self::createArrayFromProvincesOrCities($cities, $array);
                // }
                
                
                if ($provinceID) {
                    $array = self::createArrayFromProvincesOrCities($cities, $array);
                }else {
                    $array = self::createArrayFromProvincesOrCities($provinces, $array);
                }

                $data = DB::table('road_patrols')
                            ->select('province_id', 'province_fa', DB::raw('count(*) as count'))
                            ->groupBy('province_id')
                            ->when($provinceID, function ($query, $provinceID) {
                                return $query->where('province_id', $provinceID)
                                    ->select('city_id', 'city_fa', DB::raw('count(*) as count'))
                                    ->groupBy('city_id');
                            })
                            ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                            })
                            ->get();

                $array = self::createDataArray($data, $array);
                
                break;
            
            case 4:
                if (! $provinceID) {
                    $array = self::createArrayFromProvincesOrCities($provinces, $array);
                }

                if ($provinceID) {
                    $array = self::createArrayFromProvincesOrCities($cities, $array);
                }
                $data = RoadObserved::select('rms_province_id as province_id', 'ProvinceName as province_fa', 'rms_status as status')
                
                            ->when($provinceID, function ($query, $provinceID) {
                                return $query->where('rms_province_id', $provinceID)
                                    ->select('rms_city_id as city_id', 'TownName as city_fa', 'rms_status as status');
                            })
                            ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                            })
                            ->get();
                $dataAfter = [];
                if($provinceID) {
                    foreach ($data as $key => $value) {
                        $dataAfter[$value->city_id - 1]['city_fa'] = $value->city_fa;
                        $dataAfter[$value->city_id - 1]['city_id'] = $value->city_id;
                        if(!isset($dataAfter[$value->city_id - 1]['count_number'])) $dataAfter[$value->city_id - 1]['count_number'] = 0;
                        $dataAfter[$value->city_id - 1]['count_number']++;
                        if(!isset($dataAfter[$value->city_id - 1]['count'])) $dataAfter[$value->city_id - 1]['count'] = 0;
                        if($value->status != 0) {
                            $dataAfter[$value->city_id - 1]['count']++;
                        }
                    }
                } else {
                    foreach ($data as $key => $value) {
                        $dataAfter[$value->province_id - 1]['province_fa'] = $value->province_fa;
                        $dataAfter[$value->province_id - 1]['province_id'] = $value->province_id;
                        if(!isset($dataAfter[$value->province_id - 1]['count_number'])) $dataAfter[$value->province_id - 1]['count_number'] = 0;
                        $dataAfter[$value->province_id - 1]['count_number']++;
                        if(!isset($dataAfter[$value->province_id - 1]['count'])) $dataAfter[$value->province_id - 1]['count'] = 0;
                        if($value->status != 0) {
                            $dataAfter[$value->province_id - 1]['count']++;
                        }
                    }
                }
                $array = self::createDataArray($dataAfter, $array);
                // dd($array);
                $array_for_number = self::createDataArrayForCountNumber($dataAfter, $array);
                break;
            case 5:
                if (! $provinceID) {
                    $array = self::createArrayFromProvincesOrCities($provinces, $array);
                }

                if ($provinceID) {
                    $array = self::createArrayFromProvincesOrCities($cities, $array);
                }

                $data = DB::table('accident_points')
                            ->select('province_id', 'province as province_fa', DB::raw('count(*) as count'))
                            ->groupBy('province_id')
                            ->get();

                $array = self::createDataArray($data, $array);

                break;
            case 6:
                if (! $provinceID) {
                    $array = self::createArrayFromProvincesOrCities($provinces, $array);
                }

                if ($provinceID) {
                    $array = self::createArrayFromProvincesOrCities($cities, $array);
                }
                $data = DB::table('danger_points')
                            ->select('province_id', 'province_fa', DB::raw('count(*) as count'))
                            ->groupBy('province_id')
                            ->when($provinceID, function ($query, $provinceID) {
                                return $query->where('province_id', $provinceID)
                                    ->select('city_id as city_id', DB::raw('count(*) as count'))
                                    ->groupBy('city_id');
                            })
                            ->get();
                
                $array = self::createDataArray($data, $array);
                break;
            case 7:
                if (! $provinceID) {
                    $array = self::createArrayFromProvincesOrCities($provinces, $array);
                }

                if ($provinceID) {
                    $array = self::createArrayFromProvincesOrCities($cities, $array);
                }
                
                $data = DB::table('camps')
                            ->select('province_id', 'province_id', DB::raw('count(*) as count , city_id'))
                            ->groupBy('province_id')
                            ->when($provinceID, function ($query, $provinceID) {
                                return $query->where('province_id', $provinceID)
                                    ->select('city_1_fa', DB::raw('count(*) as count, city_id'))
                                    ->groupBy('cities_id');
                            })
                            ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                            })
                            ->get();

                $array = self::createDataArray($data, $array);
                break;
            default:
                return response()->json([
                    'status' => 'failed',
                    'message' => 'Request is NULL'
                ]);
                break;
        }

        $finalArray = [];
        if ($subjectID == 1 || $subjectID == 4) {
            foreach ($array['label'] as $index => $value) {
                if ($array_for_number['data'][$index] == NULL ) {
                    $finalArray['label'][] = $value;
                    $finalArray['data'][] = NULL;
                } else {
                    $finalArray['label'][] = $value." (".$array_for_number['data'][$index].")";
                    $finalArray['data'][] = $array['data'][$index];
                }
            }
        }else {
            foreach ($array['label'] as $index => $value) {
                $finalArray['label'][] = $value;
                $finalArray['data'][] = $array['data'][$index];
            }
        }
        $geoJsonArray = $finalArray['data'];

        array_multisort($finalArray['data'], SORT_DESC, $finalArray['label']);
        
        $myArray = [];

        $myArray['labels'] = $finalArray['label'];
        $myArray['datasets'][] = [
            'label' => 'نمودار وضعیت',
            'data' => $finalArray['data']
        ];

        return response()->json([
            'status' => 'success',
            'data' => $myArray,
            'geojson' => $geoJsonArray
        ]);
    }

    public function getDiagramForTile(Request $request)
    {
        $subjectID = $request->subject_id;
        $provinceID = $request->province_id;
        $dateFrom = $request->from_date;
        $dateTo = $request->to_date;

        $todayDate = Carbon::now()->format('Y-m-d');
        $provinces = Province::select('id', 'name_fa')->get();
        $cities = City::select('id', 'name_fa')
                        ->where("type_id", 1)
                        ->when($provinceID, function ($query, $provinceID) {
                            return $query->where('province_id', $provinceID);
                        })
                        ->get();
        $array = [];

        foreach ($cities as $key => $value) {
            $array['label'][$value->id] = $value->name_fa;
            $array['data'][$value->id] = null;
        }
        
        switch ($subjectID) {
            case 1:
                $array = self::createArrayFromProvincesOrCities($cities, $array);

                $data = DB::table('contract_subitems')
                            ->where('progress_project', '!=', null)
                            ->select('city_id', 'city_fa', DB::raw('round(avg(progress_project), 1) as count'))
                            ->groupBy('city_id')
                            ->when($provinceID, function ($query, $provinceID) {
                                return $query->where('province_id', $provinceID)
                                    ->select('city_id', 'city_fa', DB::raw('round(avg(progress_project), 1) as count'));
                            })
                            ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                return $query->whereBetween('contract_date_from_parent_contract', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                            })
                            ->get();

                $array = self::createDataArray($data, $array);
                break;
            case 2:
                $array = self::createArrayFromProvincesOrCities($cities, $array);
                
                $data = DB::table('road_items_projects')
                            ->select('city_id', 'city_fa', DB::raw('count(*) as count'))
                            ->groupBy('city_id')
                            ->when($provinceID, function ($query, $provinceID) {
                                return $query->where('province_id', $provinceID)
                                    ->select('city_id', 'city_fa', DB::raw('count(*) as count'));
                            })
                            ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                            })
                            ->get();
                
                $array = self::createDataArray($data, $array);
                
                break;
            case 3:
                $array = self::createArrayFromProvincesOrCities($cities, $array);
                
                $data = DB::table('road_patrol_projects')
                            ->select('city_id', 'city_fa', DB::raw('count(*) as count'))
                            ->groupBy('city_id')
                            ->when($provinceID, function ($query, $provinceID) {
                                return $query->where('province_id', $provinceID)
                                    ->select('city_id', 'city_fa', DB::raw('count(*) as count'));
                            })
                            ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                            })
                            ->get();

                $array = self::createDataArray($data, $array);
                
                break;
            
            case 4:
                $array = self::createArrayFromProvincesOrCities($cities, $array);

                $data = RoadObserved::select('rms_city_id as city_id', 'TownName as city_fa', DB::raw('count(*) as count'))
                            ->groupBy('rms_city_id')
                            ->where('rms_status', '!=', 0)
                            
                            ->when($provinceID, function ($query, $provinceID) {
                                return $query->where('rms_province_id', $provinceID)
                                    ->select('rms_city_id as city_id', 'TownName as city_fa', DB::raw('count(*) as count'));
                            })
                            ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                            })
                            ->get();

                $array = self::createDataArray($data, $array);
                break;
            case 5:
                $array = self::createArrayFromProvincesOrCities($cities, $array);

                $data = DB::table('accident_points')
                            ->select('province_id', 'province as province_fa', DB::raw('count(*) as count'))
                            ->groupBy('province_id')
                            ->when($provinceID, function ($query, $provinceID) {
                                return $query->where('province_id', $provinceID)
                                    ->select('city_id as city_id', DB::raw('count(*) as count'))
                                    ->groupBy('city_id');
                            })
                            ->get();

                $array = self::createDataArray($data, $array);
                break;
            case 6:
                if (! $provinceID) {
                    $array = self::createArrayFromProvincesOrCities($provinces, $array);
                }

                if ($provinceID) {
                    $array = self::createArrayFromProvincesOrCities($cities, $array);
                }

                $data = DB::table('danger_points')
                            ->select('city_id', 'city_fa', DB::raw('count(*) as count'))
                            ->groupBy('city_id')
                            ->when($provinceID, function ($query, $provinceID) {
                                return $query->where('province_id', $provinceID)
                                    ->select('city_id', DB::raw('count(*) as count'));
                            })
                            ->get();
                $array = self::createDataArray($data, $array);
                break;
            case 7:
                if (! $provinceID) {
                    $array = self::createArrayFromProvincesOrCities($provinces, $array);
                }

                if ($provinceID) {
                    $array = self::createArrayFromProvincesOrCities($cities, $array);
                }
 
                $data = DB::table('camps')
                            ->select('city_1_fa', DB::raw('count(*) as count, city_id'))
                            ->groupBy('cities_id')
                            ->when($provinceID, function ($query, $provinceID) {
                                return $query->where('province_id', $provinceID)
                                    ->select('city_1_fa', DB::raw('count(*) as count, city_id'));
                            })
                            ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                            })
                            ->get();
                $array = self::createDataArray($data, $array);
                break;
            default:
                return response()->json([
                    'status' => 'failed',
                    'message' => 'Request is NULL'
                ]);
                break;
        }


        return response()->json([
            'message' => 'success',
            'data' => $array
        ]);
    }
    
    public static function createDataArray($data, $array)
    {   
        if(gettype($data) == 'array') {
            foreach ($data as $key => $item) {
                // $item['province_id'] = $item['province_id'] ?? 'استان نامشخص';
                $array['data'][($item['province_id'] ?? $item['city_id'] ?? 'استان نامشخص')] = $item['count'];
            }    
        } else {
            foreach ($data as $key => $item) {
                $array['data'][($item->province_id ?? $item->city_id ?? 'استان نامشخص' )] = $item->count;
            }    
        }
        
        return $array;
    }

    public static function createDataArrayForCountNumber($data, $array)
    {   
        if(gettype($data) == 'array') {
            foreach ($data as $key => $item) {
                $array['data'][($item['province_id'] ?? $item['city_id'] )] = $item['count_number'];
            }    
        } else {
            foreach ($data as $key => $item) {
                $array['data'][($item->province_id ?? $item->city_id)] = $item->count_number;
            }
        }
        
        return $array;
    }

    public static function createArrayFromProvincesOrCities($collection, $array,$default = null)
    {
        $newArray = [];
        foreach ($collection as $key => $value) {
            $array['label'][$value->id] = $value->name_fa;
            $array['data'][$value->id] = $default;
        }

        return $array;
    }

    public function getItems()
    {
        $items = \App\Models\InfoItem::select('item as id', 'item_str')->groupBy('item')->get();
        return response()->json([
            'status' => 'success',
            'data' => $items
        ]);
    }

    public function TollhousesCount(Request $request)
    {
        $province = $request->province_id;
        $city = $request->city_id;
        
        switch ($request->type) {
            case '1':
                $data = RahdariPoint::where('status', '!=', 0)
                                    ->when($province, function ($query, $province) {
                                        return $query->where('province_id', $province);
                                    })
                                    ->when($city, function ($query, $city) {
                                        return $query->where('city_id', $city);
                                    })
                                    ->count();
                break;
            
            default:
                # code...
                break;
        }
        return response()->json([
            'message' => 'success',
            'data' => $data
        ]);
    }

    public function averagePhysicalProgressRahdariProjects(Request $request)
    {
        $dateFrom = $request->from_date;
        $dateTo = $request->to_date;
        $provinceID = $request->province_id;
        $cityID = $request->city_id;

        $avg = DB::table('contract_subitems')
                        ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                            return $query->whereBetween('contract_date_from_parent_contract', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                        })
                        ->when($provinceID, function ($query, $provinceID) {
                            return $query->where('province_id', $provinceID);
                        })
                        ->when($cityID, function ($query, $cityID) {
                            return $query->where('city_id', $cityID);
                        })
                        ->avg('progress_project');
                        
        

        return response()->json([
            'message' => 'success',
            'data' => round($avg) ?? 0
        ]);
    }

    public function separationProjectTypeRahdariProjects(Request $request)
    {
        $dateFrom = $request->from_date;
        $dateTo = $request->to_date;
        $provinceID = $request->province_id;
        $cityID = $request->city_id;
        

        $collection = ContractSubItems::groupBy('project_type_id')
                                        ->select('project_type_id as id', 'project_type_fa_for_chart as label')
                                        ->get();
        $array = [];
        foreach ($collection as $key => $value) {
            $array['label'][$value->id] = $value->label;
            $array['data'][$value->id] = 0;
        }


        $data = DB::table('contract_subitems')
                    ->groupBy('project_type_id')
                    ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                        return $query->whereBetween('contract_date_from_parent_contract', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                    })
                    ->when($provinceID, function ($query, $provinceID) {
                        return $query->where('province_id', $provinceID);
                    })
                    ->when($cityID, function ($query, $cityID) {
                        return $query->where('city_id', $cityID);
                    })
                    ->select('project_type_id as id', 'project_type_fa_for_chart as label', DB::raw('count(*) as count'))
                    ->get();

        foreach ($data as $key => $item) {
            $array['data'][$item->id] = $item->count;
        }
        
        
        $finalArray = [];
        foreach ($array['label'] as $value) {
            $finalArray['label'][] = $value;
        }
        foreach ($array['data'] as $value) {
            $finalArray['data'][] = $value;
        }

        $myArray = [];

        $myArray['labels'] = $finalArray['label'];
        $myArray['datasets'][] = [
            'label' => 'به تفکیک نوع پروژه های راهداری',
            'data' => $finalArray['data']
        ];

        return response()->json([
            'message' => 'success',
            'data' => $myArray
        ]);
    }

    public function separationLastStatusRahdariProjects(Request $request)
    {
        $dateFrom = $request->from_date;
        $dateTo = $request->to_date;
        $provinceID = $request->province_id;
        $cityID = $request->city_id;
        

        $collection = ContractSubItems::groupBy('last_status_id')
                                        ->where('last_status_id', '!=', '0')
                                        ->select('last_status_id as id', 'last_status_fa_for_chart as label')
                                        ->get();
        $array = [];
        foreach ($collection as $key => $value) {
            $array['label'][$value->id] = $value->label;
            $array['data'][$value->id] = 0;
        }


        $data = DB::table('contract_subitems')
                    ->where('last_status_id', '!=', '0')
                    ->groupBy('last_status_id')
                    ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                        return $query->whereBetween('contract_date_from_parent_contract', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                    })
                    ->when($provinceID, function ($query, $provinceID) {
                        return $query->where('province_id', $provinceID);
                    })
                    ->when($cityID, function ($query, $cityID) {
                        return $query->where('city_id', $cityID);
                    })
                    ->select('last_status_id as id', 'last_status_fa as label', DB::raw('count(*) as count'))
                    ->get();

        foreach ($data as $key => $item) {
            $array['data'][$item->id] = $item->count;
        }

        $finalArray = [];
        foreach ($array['label'] as $value) {
            $finalArray['label'][] = $value;
        }
        foreach ($array['data'] as $value) {
            $finalArray['data'][] = $value;
        }

        $myArray = [];

        $myArray['labels'] = $finalArray['label'];
        $myArray['datasets'][] = [
            'label' => 'تفکیک به آخرین وضعیت پروژه',
            'data' => $finalArray['data']
        ];
        
        return response()->json([
            'message' => 'success',
            'data' => $myArray
        ]);
    }

    public function separationAxisTypeRahdariProjects(Request $request)
    {
        $dateFrom = $request->from_date;
        $dateTo = $request->to_date;
        $provinceID = $request->province_id;
        $cityID = $request->city_id;
        

        $collection = ContractSubItems::groupBy('axis_type_id')
                                        ->select('axis_type_id as id', 'axis_type_fa as label')
                                        ->get();
        $array = [];
        foreach ($collection as $key => $value) {
            $array['label'][$value->id] = $value->label;
            $array['data'][$value->id] = 0;
        }


        $data = DB::table('contract_subitems')
                    ->groupBy('axis_type_id')
                    ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                        return $query->whereBetween('contract_date_from_parent_contract', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                    })
                    ->when($provinceID, function ($query, $provinceID) {
                        return $query->where('province_id', $provinceID);
                    })
                    ->when($cityID, function ($query, $cityID) {
                        return $query->where('city_id', $cityID);
                    })
                    ->select('axis_type_id as id', 'axis_type_fa as label', DB::raw('count(*) as count'))
                    ->get();

        foreach ($data as $key => $item) {
            $array['data'][$item->id] = $item->count;
        }

        $finalArray = [];
        foreach ($array['label'] as $value) {
            $finalArray['label'][] = $value;
        }
        foreach ($array['data'] as $value) {
            $finalArray['data'][] = $value;
        }
        
        $myArray = [];

        $myArray['labels'] = $finalArray['label'];
        $myArray['datasets'][] = [
            'label' => 'تفکیک به نوع محور',
            'data' => $finalArray['data']
        ];

        

        return response()->json([
            'message' => 'success',
            'data' => $myArray
        ]);
    }

    public function percentComplaintsHandled(Request $request)
    {
        $dateFrom = $request->from_date;
        $dateTo = $request->to_date;
        $provinceID = $request->province_id;
        $cityID = $request->city_id;

        $countHandled = RoadObserved::when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                        return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                    })
                    ->when($provinceID, function ($query, $provinceID) {
                        return $query->where('rms_province_id', $provinceID);
                    })
                    ->when($cityID, function ($query, $cityID) {
                        return $query->where('rms_city_id', $cityID);
                    })
                    ->where('rms_status', "<>",0)
                    ->count();
                    
        $countAll = RoadObserved::when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                        return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                    })
                    ->when($provinceID, function ($query, $provinceID) {
                        return $query->where('rms_province_id', $provinceID);
                    })
                    ->when($cityID, function ($query, $cityID) {
                        return $query->where('rms_city_id', $cityID);
                    })
                    ->count();

        $percent = $countAll ? ($countHandled / $countAll) * 100 : 0;

        return response()->json([
            'message' => 'success',
            'data' => round($percent) ?? 0
        ]);
    }

    public function CountByNumbersAccidentPoints(Request $request)
    {
        $provinceID = $request->province_id;

        $collection = AccidentPoint::groupBy('geometric_desc')
                                        ->select('geometric_desc as label')
                                        ->get();
        $array = [];
        foreach ($collection as $key => $value) {
            $array['label'][$value->label] = $value->label;
            $array['data'][$value->label] = 0;
        }

        $data = DB::table('accident_points')
                    ->groupBy('geometric_desc')
                    ->when($provinceID, function ($query, $provinceID) {
                        return $query->where('province_id', $provinceID);
                    })
                    ->select('geometric_desc as label', DB::raw('count(*) as count'))
                    ->get();

        foreach ($data as $key => $item) {
            $array['data'][$item->label] = $item->count;
        }

        $finalArray = [];
        foreach ($array['label'] as $value) {
            $finalArray['label'][] = $value;
        }
        foreach ($array['data'] as $value) {
            $finalArray['data'][] = $value;
        }

        $myArray = [];

        $myArray['labels'] = $finalArray['label'];
        $myArray['datasets'][] = [
            'label' => 'تفکیک هندسی',
            'data' => $finalArray['data']
        ];

        
        return response()->json([
            'message' => 'success',
            'data' => $myArray
        ]);
    }

    public function CountAccidentPoints(Request $request)
    {
        $provinceID = $request->province_id;
        
        $data = DB::table('accident_points')
                    ->where('end_date', '!=', null)
                    ->count();
        $percent = ($data / AccidentPoint::count()) * 100;

        return response()->json([
            'message' => 'success',
            'data' => round($percent)
        ]);
    }


    public function roadItemProjectItemChart(Request $request)
    {
        $itemId = $request->item_id;
        $dateFrom = $request->from_date;
        $dateTo = $request->to_date;
        $provinceID = $request->province_id ?? null;
        $cityID = $request->city_id ?? null;

        
        $start = microtime(true);
        $data = DB::table('road_items_projects')
        ->select('sub_item_fa as label', DB::raw('count(*) as count'))
        ->where('item', $itemId)
        ->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59'])
        ->when($provinceID, function ($query, $provinceID) {
            return $query->where('province_id', $provinceID);
        })
        ->when($cityID, function ($query, $cityID) {
            return $query->where('city_id', $cityID);
        })
        ->groupBy('sub_item')
        ->get();
        $end = microtime(true);
        
        $sub_item = \App\Models\InfoItem::select('item as id', 'sub_item_str')
        ->where('item', $itemId)
        ->get();
        
        $finalArray = [];
        foreach ($sub_item as $value) {
            $finalArray['label'][] = $value->sub_item_str;
            $temp = $data->where('label', $value->sub_item_str)->first();
            if ($temp) {
                $finalArray['data'][] = $temp->count;
            } else {
                $finalArray['data'][] = 0;
            }
        }

        $myArray = [];

        $myArray['labels'] = $finalArray['label'];
        $myArray['datasets'][] = [
            'label' => 'به تفکیک نوع پروژه های راهداری',
            'data' => $finalArray['data']
        ];
        $diff = $end - $start;
        return response()->json([
            'message' => 'success',
            'data' => $myArray
        ]);
    }

    public function separationActivityTypeRahdariActivities(Request $request)
    {
        ini_set('memory_limit', '-1');
        $dateFrom = $request->from_date;
        $dateTo = $request->to_date;
        $provinceID = $request->province_id ?? null;
        $cityID = $request->city_id ?? null;

        $finalArray = [];

        foreach (InfoItem::groupby('item')->get() as $key => $value) {
            $finalArray['label'][$value['item']] = $value['item_str'];
            $finalArray['data'][$value['item']] = 0;
        }
        $data = DB::table('road_items_projects')
                    ->select('item_fa as label', 'item')
                    ->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59'])
                    ->when($provinceID, function ($query, $provinceID) {
                        return $query->where('province_id', $provinceID);
                    })
                    ->when($cityID, function ($query, $cityID) {
                        return $query->where('city_id', $cityID);
                    })
                    ->get();

        $dataAfter = array();
        foreach ($data as $key => $value)  {
            $dataAfter[$value->item]['label'] = $value->label;
            if(!isset($dataAfter[$value->item]['count'])) $dataAfter[$value->item]['count'] =0;
                    $dataAfter[$value->item]['count']++;

        }

        foreach ($dataAfter as $key => $value) {
            $finalArray['label'][$key] = $value['label'];
            $finalArray['data'][$key] = $value['count'];
        }

        $temporary = [];
        foreach ($finalArray['label'] as $value) {
            $temporary['label'][] = $value;
        }

        foreach ($finalArray['data'] as $value) {
            $temporary['data'][] = $value;
        }
        array_multisort($temporary['data'], SORT_DESC, $temporary['label']);
        
        $myArray = [];

        $myArray['labels'] = $temporary['label'];
        $myArray['datasets'][] = [
            'label' => 'به تفکیک نوع پروژه های راهداری',
            'data' => $temporary['data']
        ];

        return response()->json([
            'message' => 'success',
            'data' => $myArray
        ]);
    }

    public function separationComplainTypeRahdariComplains(Request $request)
    {
        $dateFrom = $request->from_date;
        $dateTo = $request->to_date;
        $provinceID = $request->province_id;
        $cityID = $request->city_id;

        $dataLabel = RoadObserved::select('fk_FeatureType as id', 'FeatureTypeTitle as label', DB::raw('count(*) as count'))
                                    ->groupBy('fk_FeatureType')
                                    ->get();

        $array = [];
        foreach ($dataLabel as $value) {
            $array['label'][$value->id] = $value->label;
            $array['dataVasel'][$value->id] = 0;
            $array['dataResidegiShode'][$value->id] = 0;
        }
        $dataResidegiShode = RoadObserved::where('rms_status', '!=', 0)
                                            
                                            ->select('fk_FeatureType as id', DB::raw('count(*) as count'))
                                            ->when($provinceID, function ($query, $provinceID) {
                                                return $query->where('rms_province_id', $provinceID);
                                            })
                                            ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                                return $query->whereBetween('created_at', [$dateFrom, $dateTo]);
                                            })
                                            ->when($cityID, function ($query, $cityID) {
                                                return $query->where('rms_city_id', $cityID);
                                            })
                                            ->groupBy('fk_FeatureType')
                                            ->get();

        foreach ($dataResidegiShode as $key => $item) {
            $array['dataResidegiShode'][$item->id] = $item->count;
        }

        $dataVasel = RoadObserved::select('fk_FeatureType as id', DB::raw('count(*) as count'))
                                    ->when($provinceID, function ($query, $provinceID) {
                                        return $query->where('rms_province_id', $provinceID);
                                    })
                                    ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                                        return $query->whereBetween('created_at', [$dateFrom, $dateTo]);
                                    })
                                    ->when($cityID, function ($query, $cityID) {
                                        return $query->where('rms_city_id', $cityID);
                                    })
                                    
                                    ->groupBy('fk_FeatureType')
                                    ->get();


        foreach ($dataVasel as $key => $item) {
            $array['dataVasel'][$item->id] = $item->count;
        }

        $finalArray = [];
        foreach ($array['label'] as $value) {
            $finalArray['label'][] = $value;
        }
        foreach ($array['dataResidegiShode'] as $value) {
            $finalArray['dataResidegiShode'][] = $value;
        }
        foreach ($array['dataVasel'] as $value) {
            $finalArray['dataVasel'][] = $value;
        }
        

        $myArray = [];

        $myArray['labels'] = $finalArray['label'];
        $myArray['datasets'][] = [
            'label' => 'رسیدگی شده',
            'data' => $finalArray['dataResidegiShode']
        ];
        $myArray['datasets'][] = [
            'label' => 'واصل شده',
            'data' => $finalArray['dataVasel']
        ];
        
        return response()->json([
            'message' => 'success',
            'data' => $myArray ?? null
        ]);
    }

    public function primaryEstimatesDamages(Request $request)
    {
        return response()->json([
            'message' => 'success',
            'data' => Camp::where('is_open', 2)->sum('blockage_damage_money')
        ]);
    }

    public function totalLengthDamagedAxes(Request $request)
    {
        $dateFrom = $request->from_date;
        $dateTo = $request->to_date;
        $provinceID = $request->province_id;
        $cityID = $request->city_id;

        $camps = DB::table('camps')
                    ->when($dateFrom, function ($query) use ($dateFrom, $dateTo) {
                        return $query->whereBetween('created_at', [$dateFrom . ' 00:00:00', $dateTo . ' 23:59:59']);
                    })
                    ->when($provinceID, function ($query, $provinceID) {
                        return $query->where('province_id', $provinceID);
                    })
                    ->when($cityID, function ($query, $cityID) {
                        return $query->where('cities_id', $cityID);
                    })
                    ->sum('blockage_length');
        

        return response()->json([
            'message' => 'success',
            'data' => round($camps, 2)
        ]);
    }
}
