<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hekmatinasser\Verta\Verta;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Spatie\Permission\Models\Permission;
use App\Models\User;
use Carbon\Carbon;
use App\Models\City;
use App\Models\Province;
use Illuminate\Support\Facades\File;
use App\Models\EdarateShahri;
use App\Models\EdarateOstani;
use Cache;
use App\Models\Role;
use App\Models\HttpErorrsList;

class UserController extends Controller
{

    public function changePassword(User $user, Request $request)
    {
        $validData = $request->validate([
            'password' => 'required|string|min:8|confirmed',
        ]);
        $user->password = Hash::make($request->password);
        $user->save();
        return response()->json(['message' => "password changed successfully!!!!"], 200);
    }

    public function printGroup(User $user, Request $request)
    {
        $request->fromDate = $request->fromDate ? $request->fromDate . " 00:00:00" : Carbon::now()->format('Y-m-d 00:00:00') ;
        $request->toDate = $request->toDate ? $request->toDate . " 23:59:59" : Carbon::now()->format('Y-m-d 23:59:59');

        $data = [];

        $ids_list = '';
        // $users = $role->users()->select("*")->get()->toArray();
        // foreach ($user as $index => $item) {
        $user_activity_quantity_temp[$user->id] = [
            "majmoe" => 0,
            "name" => $user->first_name ? $user->first_name." ".$user->last_name." (".$user->username.")" : $user->name." (".$user->username.")",
        ];

        $user_activity_time_temp[$user->id] = [
            "majmoe" => 0,
            "name" => $user->first_name ? $user->first_name." ".$user->last_name." (".$user->username.")" : $user->name."(".$user->username.")",
        ];

        $user_activity_top_5_temp[$user->id] = [
            "activity_list" => [],
            "name" => $user->first_name ? $user->first_name." ".$user->last_name." (".$user->username.")" : $user->name."(".$user->username.")",
        ];


        // if (!$index) {
        $ids_list = $user->id;
        // } else {
        // $ids_list .= ",".$item['id'];
        // }
        // }
        $total_activity_time_sql = "
            SELECT sum(majmoe) AS activity FROM (SELECT *,
            COUNT(quantity) AS majmoe
            FROM (
                    SELECT user_id,
                        COUNT(*) AS quantity
                    
                            FROM user_activity_logs
                            WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(".$ids_list.")
                        
                    GROUP BY yy,
                        mm,
                        dd,
                        hh,
                        user_id
                ) user_activity_by_hour_and_
            GROUP BY user_id) AS calculated_table;";

        $quantitative_activity_chart_sql = "
            SELECT created_at,
                COUNT(*) AS quantity
            
                        FROM user_activity_logs
                    WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(".$ids_list.")
            GROUP BY 
                yy,
                mm,
                dd ;";

        $hourly_activity_chart_sql = "
            SELECT 
                COUNT(quantity) AS majmoe
            FROM (
                    SELECT yy,
                    mm,
                    dd,
                    hh,
                        COUNT(*) AS quantity
                            FROM user_activity_logs
                            WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(".$ids_list.")
                    GROUP BY yy,
                        mm,
                        dd,
                        hh,
                        user_id
                ) user_activity_by_hour_and_
            GROUP BY 
                yy,
                mm,
                dd;";

        $total_activity_quantity_sql = "
            SELECT COUNT(*) AS total_activity_quantity
            FROM user_activity_logs
            WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(".$ids_list.")
            ";


        $top_10_activity_list_sql = "
                    SELECT *,
                        COUNT(*) AS quantity
                    FROM (
                            SELECT 
                                description,
                                log_unique_code
                            FROM user_activity_logs
                            WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(".$ids_list.")
                        ) user_activity_distinct
                    GROUP BY
                        log_unique_code
                    ORDER BY  quantity desc
                    LIMIT 10";


        $user_activity_quantity_sql = "
            SELECT *,
                COUNT(*) AS quantity
            FROM (
                    SELECT 
                        user_id,
                        user_first_name,
                        user_last_name,
                        user_name,
                        username
                    FROM user_activity_logs
                    WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(".$ids_list.")
                ) user_activity_distinct
            GROUP BY user_id
            ORDER BY  quantity desc";

        $active_user_count_sql = "
            SELECT  COUNT(*) AS active_user_count
            FROM(
                SELECT 
                    user_id
                FROM user_activity_logs
                WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(".$ids_list.")
                GROUP BY user_id
            ) grpuped_by_user_id";

        $user_activity_time_sql = "
        select 
            *,
            COUNT(quantity) AS majmoe
        FROM (
                SELECT
                    user_first_name,
                    user_last_name,
                    user_name,
                    username,
                    user_id,
                    COUNT(*) AS quantity
                        FROM user_activity_logs
                        WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(".$ids_list.")
                GROUP BY yy,
                    mm,
                    dd,
                    hh,
                    user_id
            ) user_activity_by_hour_and_ 
            GROUP BY user_id
            ORDER BY majmoe desc;";

        foreach (DB::select($user_activity_quantity_sql) as $key => $value) {
            $user_activity_quantity_temp[$value->user_id] = [
                "majmoe" => $value->quantity ?? 0,
                "name" => $value->user_first_name ? $value->user_first_name." ".$value->user_last_name." (".$value->username.")" : $value->user_name." (".$value->username.")",
            ];
        }

        foreach (DB::select($user_activity_time_sql) as $key => $value) {
            $user_activity_time_temp[$value->user_id] = [
                "majmoe" => $value->majmoe ?? 0,
                "name" => $value->user_first_name ? $value->user_first_name." ".$value->user_last_name." (".$value->username.")" : $value->user_name." (".$value->username.")",
            ];
        }

        foreach ($user_activity_top_5_temp as $key => $value) {
            $user_activity_top_5_temp_sql = "
                SELECT
                    description,
                    COUNT(*) AS quantity
                FROM user_activity_logs
                WHERE user_id = {$key} AND created_at between '{$request->fromDate}' and '{$request->toDate}'
                GROUP BY log_unique_code
                ORDER BY quantity DESC
                LIMIT 5
            ";

            $activity_list = DB::select($user_activity_top_5_temp_sql);
            $sum = 0;
            foreach ($activity_list as $index => $item) {
                $sum += (int) $item->quantity;
            }
            $user_activity_top_5_temp[$key] = [
                "sum" => $sum,
                "name" => $value['name'],
                "activity_list" => $activity_list,
            ];
        }
        arsort($user_activity_top_5_temp);
        arsort($user_activity_time_temp);
        arsort($user_activity_quantity_temp);
        $data = [
            'fromDate' => $request->fromDate ? $request->fromDate : null,
            'toDate' => $request->toDate ? $request->toDate : null,
            'user_activity_time' => $ids_list ? $user_activity_time_temp : null,
            'hourly_activity_chart' => $ids_list ? DB::select($hourly_activity_chart_sql) : null,
            'quantitative_activity_chart' => $ids_list ? DB::select($quantitative_activity_chart_sql) : null,
            'total_activity_quantity' => $ids_list ? DB::select($total_activity_quantity_sql)[0]->total_activity_quantity : null,
            'total_activity_time' => $ids_list ? DB::select($total_activity_time_sql)[0]->activity : null,
            'top_10_activity_list' => $ids_list ? DB::select($top_10_activity_list_sql) : null,
            'user_activity_quantity' => $ids_list ? $user_activity_quantity_temp : null,
            'group_name' => $user->first_name." ".$user->last_name,
            'average' => round(($ids_list ? DB::select($total_activity_time_sql)[0]->activity : 0) / 1, 2) ,
            'user_activity_top_5_temp' => $user_activity_top_5_temp,
            'total_user_count' => 1,
            'active_user_count' => $ids_list ? DB::select($active_user_count_sql)[0]->active_user_count : null,
            'group_id' => $user->id
            ];

        return View('word.user-activity-individual', compact('data'));
    }

    public function userActivityLogs()
    {
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => auth()->user()->activityLogs,
        ], 200);
    }

    public function index(Request $request)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1038);
        }

        $province = $request->province ?? null;
        $city = $request->city ?? null;
        $province_office = $request->province_office ?? null;

        if (Auth::user()->checkUserHasPermission('full-user-management')) {
            $users = User::when($province, function ($query, $province) {
                return $query->where('province_id', $province);
            })
            ->when($city, function ($query, $city) {
                return $query->where('city_id', $city);
            })
            ->when($province_office, function ($query, $province_office) {
                if ($province_office == -1) {
                    return $query->where('edarate_ostani_id', null)->whereNotNull('edarate_shahri_id');
                } else {
                    return $query->where('edarate_ostani_id', $province_office);
                }
            })
            ->with(['roles' => function ($query) {
                $query->where('for_report', 1);
            }])
            ->get();
        } elseif (Auth::user()->checkUserHasPermission('limited-user-management')) {
            $users = User::when($province, function ($query, $province) {
                return $query->where('province_id', $province);
            })
            ->where('province_id', Auth::user()->province_id)
            ->when($city, function ($query, $city) {
                return $query->where('city_id', $city);
            })
            ->when($province_office, function ($query, $province_office) {
                if ($province_office == -1) {
                    return $query->where('edarate_ostani_id', null)->whereNotNull('edarate_shahri_id');
                } else {
                    return $query->where('edarate_ostani_id', $province_office);
                }
            })
            ->with(['roles' => function ($query) {
                $query->where('for_report', 1);
            }])
            ->get();
        } else {
            return response()->json([
                'message' => 'Forbidden'
            ], 403);
        }

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

    public function store(Request $request)
    {
        $validData = $request->validate([
            'username' => 'string|unique:users',
            // 'national_code' => 'unique:users,national_code',
            'mobile' => 'digits:11|regex:/^09[0-9]{9}$/i',
        ]);

        $createUser = new User();

        $createUser->province_id = $request->province_id == 0 ? null : $request->province_id;
        $createUser->province_fa = ($request->province_id == 0) ? 'ستاد' : Province::find($request->province_id)->name_fa;

        $createUser->city_id = $request->city_id == 0 ? null : $request->city_id;
        $createUser->city_fa = ($request->city_id == 0) ? null : City::find($request->city_id)->name_fa ;

        if ($request->edarate_ostani_id != 'null') {
            $temp = EdarateOstani::find($request->edarate_ostani_id)->name_fa;
            $createUser->edarate_ostani_id = $request->edarate_ostani_id;
            $createUser->edarate_ostani_name = $temp;
            if ($request->province_id == 0) {
                $createUser->name = $temp .' '. $createUser->province_fa;
            } else {
                $createUser->name = $temp .' استان '. $createUser->province_fa;
            }
        } else {
            $temp = EdarateShahri::find($request->edarate_shahri_id)->name_fa;
            $createUser->edarate_shahri_id = $request->edarate_shahri_id;
            $createUser->edarate_shahri_name = $temp;

            if ($request->province_id == 0) {
                $createUser->name = $temp .' '. $createUser->province_fa;
            } else {
                $createUser->name = $temp .' استان '. $createUser->province_fa;
            }
        }

        $createUser->username = $request->username;
        $createUser->password = Hash::make($request->password);
        $createUser->first_name = $request->first_name;
        $createUser->last_name = $request->last_name;
        $createUser->position = $request->position;
        $createUser->mobile = $request->mobile;
        $createUser->degree = $request->degree;
        $createUser->major = $request->major;
        $createUser->national_code = $request->national_code;

        $createUser->save();

        if (! $request->permissions == null) {
            $createUser->syncPermissions(explode(",", $request->permissions));
        }

        $roles = $request->only('roles');
        if (! $roles == null) {
            $createUser->syncRoles($roles);
        }

        if ($request->has('avatar')) {
            $destinationPath = 'avatar/' . $request->username;
            $filename = time() .".". $request->file('avatar')->getClientOriginalExtension();
            $request->file('avatar')->storeAs($destinationPath, $filename, 'public');
            $createUser->update(['avatar' => 'storage/'.$destinationPath ."/". $filename]);
        }

        if (auth()->user()) {
            auth()->user()->addActivityComplete(1039, $createUser);
        }

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

    public function simpleAddUser(Request $request)
    {
        $request->validate([
            'province_id' => 'required',
            'username' => 'required|unique:users,username',
            // 'national_code' => 'unique:users,national_code',
            'password' => 'required'
        ]);

        $user = new User();
        $user->username = $request->username;

        $user->province_id = $request->province_id == 0 ? null : $request->province_id;
        $user->province_fa = ($request->province_id == 0) ? 'ستاد' : Province::find($request->province_id)->name_fa;

        $user->city_id = $request->city_id == 0 ? null : $request->city_id;
        $user->city_fa = ($request->city_id == 0) ? null : City::find($request->city_id)->name_fa ;

        if ($request->edarate_ostani_id != 'null') {
            $temp = EdarateOstani::find($request->edarate_ostani_id)->name_fa;
            $user->edarate_ostani_id = $request->edarate_ostani_id;
            $user->edarate_ostani_name = $temp;
            if ($request->province_id == 0) {
                $user->name = $temp .' '. $user->province_fa;
            } else {
                $user->name = $temp .' استان '. $user->province_fa;
            }
        } else {
            $temp = EdarateShahri::find($request->edarate_shahri_id)->name_fa;
            $user->edarate_shahri_id = $request->edarate_shahri_id;
            $user->edarate_shahri_name = $temp;

            if ($request->province_id == 0) {
                $user->name = $temp .' '. $user->province_fa;
            } else {
                $user->name = $temp .' استان '. $user->province_fa;
            }
        }

        $user->password = Hash::make($request->password);
        $user->national_code = $request->national_code;
        $user->save();

        if (auth()->user()) {
            auth()->user()->addActivityComplete(1039, $user);
        }

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

    public function show($id)
    {
        $user = User::where('id', $id)->with(['roles', 'permissions'])->get();
        return response()->json([
            'status' => '200',
            'message' => 'success',
            'data' => $user
        ], 200);
    }

    public function update(Request $request, User $user)
    {
        $request->validate([
            // 'national_code' => 'required|unique:users,national_code,'.$user->id,
        ]);

        if ($request->has('avatar')) {
            Storage::delete('public/' . $user->avatar);
            $destinationPath = 'avatar/' . $user->username;
            $filename = time() .".". $request->file('avatar')->getClientOriginalExtension();
            $request->file('avatar')->storeAs($destinationPath, $filename, 'public');
            $user->update(['avatar' => 'storage/'.$destinationPath ."/". $filename]);
        }

        $user->province_id = $request->province_id == 0 ? null : $request->province_id;
        $user->province_fa = ($request->province_id == 0) ? 'ستاد' : Province::find($request->province_id)->name_fa;

        $user->city_id = $request->city_id == 0 ? null : $request->city_id;
        $user->city_fa = ($request->city_id == 0) ? null : City::find($request->city_id)->name_fa ;

        if ($request->edarate_ostani_id != "null") {
            $temp = EdarateOstani::find($request->edarate_ostani_id)->name_fa;
            $user->edarate_ostani_id = $request->edarate_ostani_id;
            $user->edarate_ostani_name = $temp;

            $user->edarate_shahri_id = null;
            $user->edarate_shahri_name = null;

            if ($request->province_id == 0) {
                $user->name = $temp .' '. $user->province_fa;
            } else {
                $user->name = $temp .' استان '. $user->province_fa;
            }
        } else {
            $temp = EdarateShahri::find($request->edarate_shahri_id)->name_fa;
            $user->edarate_shahri_id = $request->edarate_shahri_id;
            $user->edarate_shahri_name = $temp;
            $user->edarate_ostani_id = null;
            $user->edarate_ostani_name = null;
            if ($request->province_id == 0) {
                $user->name = $temp .' '. $user->province_fa;
            } else {
                $user->name = $temp .' استان '. $user->province_fa;
            }
        }

        $user->first_name = $request->first_name;
        $user->last_name = $request->last_name;
        $user->position = $request->position;
        $user->mobile = $request->mobile;
        $user->degree = $request->degree;
        $user->major = $request->major;
        $user->national_code = $request->national_code;

        if (!is_null($request->password)) {
            $request->validate([
                'password' => ['string']
            ]);
            $user->password = Hash::make($request->password);
        }

        if (! $request->permissions == null) {
            $user->syncPermissions(explode(",", $request->permissions));
        }

        $roles = $request->only('roles');
        if (! $roles == null) {
            $user->syncRoles($roles);
        }

        $user->save();

        if (auth()->user()) {
            auth()->user()->addActivityComplete(1040, $user);
        }

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

    public function updateToDefaultPassword($id)
    {
        $user = User::find($id);

        $user->password = Hash::make('123');
        $user->confirmed = 0;

        $user->save();

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

    public function getUserProjects()
    {
        if (Auth::user()->username == 'drdanesh') {
            $provinces = \App\Models\Province::with('users')->get();
        } else {
            $provinces = \App\Models\Province::where('id', Auth::user()->province_id)
                ->with('users')->get();
        }

        $projectsCount = [];
        $projectsList = [];
        $projectsList['roadItemsProjects'] = 0;
        $projectsList['roadConstructionProjects'] = 0;
        $projectsList['roadPatrolProjects'] = 0;
        $projectsList['abrarPlanProjects'] = 0;

        foreach ($provinces as $province) {
            if ($province->id == Auth::user()->province_id) {
                $projectsList['province'] = $province->name_fa;
                $projectsList['projects'] = $province->roadItemsProjects()->orderByDesc('created_at')->limit(10)->get();
            }

            $projectsCount[$province->name_fa] = [];

            $projectsCount[$province->name_fa]['name'] = $province->name_fa;
            $projectsCount[$province->name_fa]['roadItemsProjects'] = $province->roadItemsProjects()->count();
            $projectsCount[$province->name_fa]['roadConstructionProjects'] = $province->roadConstructionProjects()->count();
            $projectsCount[$province->name_fa]['roadPatrolProjects'] = $province->roadPatrolProjects()->count();
            $projectsCount[$province->name_fa]['abrarPlanProjects'] = $province->abrarPlanProjects()->count();

            $projectsList['roadItemsProjects'] += $projectsCount[$province->name_fa]['roadItemsProjects'];
            $projectsList['roadConstructionProjects'] += $projectsCount[$province->name_fa]['roadConstructionProjects'];
            $projectsList['roadPatrolProjects'] += $projectsCount[$province->name_fa]['roadPatrolProjects'];
            $projectsList['abrarPlanProjects'] += $projectsCount[$province->name_fa]['abrarPlanProjects'];
        }

        return view('rmto-preview.pages.management.user-projects-list', [
            'projects' => $projectsCount,
            'projectsList' => $projectsList
        ]);
    }

    public function getProvinceProjectsCount(Request  $request)
    {
        $request->validate([
            'start-date' => 'date_format:Y-m-d',
            'end-date' => 'date_format:Y-m-d'
        ]);

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

        $users = User::where('province_id', '=', Auth::user()->province_id)
            ->whereNotBetween('id', [466, 470])
            ->get();

        $projectsCount = [];
        $countIndex = 0;

        $roadItemsCount = 0;
        $roadPatrolCount = 0;
        $roadConstructionCount = 0;
        $cityProjectsCount = 0;

        foreach ($users as $user) {
            $projectsCount[$countIndex]['province_id'] = $user->province->id;
            $projectsCount[$countIndex]['province_name'] = $user->province->name_fa;
            $projectsCount[$countIndex]['user_id'] = $user->id;
            $projectsCount[$countIndex]['user_name'] = $user->name;
            $projectsCount[$countIndex]['roadItemsProjects'] = $user->roadItemsProjects()
                ->where('item', '<', '17')
                ->whereBetween('created_at', [$startDate, $endtDate])->count();
            $roadPatrolProjects = $user->roadPatrolProjects()
                ->whereBetween('created_at', [$startDate, $endtDate])->get();
            $projectsCount[$countIndex]['roadPatrolProjects'] = $roadPatrolProjects->count();

            $projectsCount[$countIndex]['roadPatrolSubProjects'] = 0;

            foreach ($roadPatrolProjects as $roadPatrolProject) {
                $projectsCount[$countIndex]['roadPatrolSubProjects'] += $roadPatrolProject->roadPatrolSubProjects()
                    ->where('item', '<', '17')->count();
            }

            $projectsCount[$countIndex]['roadConstructionProjects'] = $user->roadConstructionProjects()
                ->whereBetween('created_at', [$startDate, $endtDate])->count();

            $projectsCount[$countIndex]['projectsCount'] = $projectsCount[$countIndex]['roadItemsProjects']
                + $projectsCount[$countIndex]['roadPatrolProjects']
                + $projectsCount[$countIndex]['roadConstructionProjects'];

            $roadItemsCount += $projectsCount[$countIndex]['roadItemsProjects'];
            $roadPatrolCount += $projectsCount[$countIndex]['roadPatrolProjects'];
            $roadConstructionCount += $projectsCount[$countIndex]['roadConstructionProjects'];
            $cityProjectsCount += $projectsCount[$countIndex]['projectsCount'];

            $countIndex++;
        }

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => [
                'projects' => $projectsCount,
                'count' => [
                    'roadItemsCount' => $roadItemsCount,
                    'roadPatrolCount' => $roadPatrolCount,
                    'roadConstructionCount' => $roadConstructionCount,
                    'totalCount' => $cityProjectsCount
                ]
            ]
        ], 200);
    }

    public function getProvinceProjectsItem(Request  $request)
    {
        $request->validate([
            'start-date' => 'date_format:Y-m-d',
            'end-date' => 'date_format:Y-m-d'
        ]);

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

        $province = \App\Models\Province::find(Auth::user()->province_id);
        $roadItemsProjects = $province->roadItemsProjects()
            ->where('road_items_projects.item', '<', '17')
            ->whereBetween('road_items_projects.created_at', [$startDate, $endtDate])
            ->get();
        $roadPatrolProjects = $province->roadPatrolProjects()
            ->whereBetween('road_patrol_projects.created_at', [$startDate, $endtDate])
            ->get();

        $projectCollection = new \Illuminate\Support\Collection();
        $projectCollectionTemp = new \Illuminate\Support\Collection();

        foreach ($roadItemsProjects as $roadItemsProject) {
            if ($roadItemsProject->user->username == 'witel' || $roadItemsProject->user->username == 'drdanesh') {
                continue;
            }
            if (Auth::user()->province_id != null && Auth::user()->city_id == null && Auth::user()->id <= 470) {
                if ($roadItemsProject->created_at->isToday() || $roadItemsProject->created_at->isYesterday()) {
                    $canDelete = 1;
                } else {
                    $canDelete = 0;
                }
            } elseif (Auth::user()->id == $roadItemsProject->user->id) {
                if ($roadItemsProject->created_at->isToday()) {
                    $canDelete = 1;
                } else {
                    $canDelete = 0;
                }
            } else {
                $canDelete = 0;
            }

            if (($roadItemsProject->sub_items != null && $roadItemsProject->sub_items_data != null)
                && sizeof($roadItemsProject->sub_items) > 0) {
                $dataKeys = array_keys($roadItemsProject->sub_items_data);

                foreach ($roadItemsProject->sub_items as $key => $subItem) {
                    $subItemData = null;

                    if (isset($dataKeys[$key])) {
                        $subItemData = [
                            $dataKeys[$key] => $roadItemsProject->sub_items_data[$dataKeys[$key]]
                        ];
                    }

                    $project = [
                        'id' => $roadItemsProject->id,
                        'user' => $roadItemsProject->user->name,
                        'type' => 'فعالیت روزانه و جاری راهداری',
                        'item' => $roadItemsProject->item,
                        'sub_items' => [$subItem],
                        'sub_items_data' => $subItemData,
                        'created_at_jalali' => verta($roadItemsProject->created_at)->format('Y/m/d - H:i'),
                        'created_at' => $roadItemsProject->created_at->toDateTimeString(),
                        'can_delete' => $canDelete
                    ];

                    $projectCollection->add($project);
                }
            } else {
                $project = [
                    'id' => $roadItemsProject->id,
                    'user' => $roadItemsProject->user->name,
                    'type' => 'فعالیت روزانه و جاری راهداری',
                    'item' => $roadItemsProject->item,
                    'sub_items' => $roadItemsProject->sub_items,
                    'sub_items_data' => $roadItemsProject->sub_items_data,
                    'created_at_jalali' => verta($roadItemsProject->created_at)->format('Y/m/d - H:i'),
                    'created_at' => $roadItemsProject->created_at->toDateTimeString(),
                    'can_delete' => $canDelete
                ];

                $projectCollection->add($project);
            }
        }

        foreach ($roadPatrolProjects as $roadPatrolProject) {
            if ($roadPatrolProject->user->username == 'witel' || $roadPatrolProject->user->username == 'drdanesh') {
                continue;
            }

            $subProjects = $roadPatrolProject->roadPatrolSubProjects()
                ->where('item', '<', '17')->get();

            $subItems = [];

            foreach ($subProjects as $key => $subProject) {
                $subItems[$key] = [
                    'item' => $subProject->item,
                    'sub_items' => $subProject->sub_items,
                    'sub_items_data' => $subProject->sub_items_data
                ];
            }

            if (Auth::user()->province_id != null && Auth::user()->city_id == null && Auth::user()->id <= 470) {
                if ($roadPatrolProject->created_at->isToday() || $roadPatrolProject->created_at->isYesterday()) {
                    $canDelete = 1;
                } else {
                    $canDelete = 0;
                }
            } elseif (Auth::user()->id == $roadPatrolProject->user->id) {
                if ($roadPatrolProject->created_at->isToday()) {
                    $canDelete = 1;
                } else {
                    $canDelete = 0;
                }
            } else {
                $canDelete = 0;
            }

            $project = [
                'id' => $roadPatrolProject->id,
                'user' => $roadPatrolProject->user->name,
                'type' => 'گشت راهداری و ترابری',
                'created_at_jalali' => verta($roadPatrolProject->created_at)->format('Y/m/d - H:i'),
                'created_at' => $roadPatrolProject->created_at->toDateTimeString(),
                'sub_projects' => $subItems,
                'can_delete' => $canDelete
            ];
            $projectCollection->add($project);
        }

        $projectCollection = $projectCollection->sortByDesc('created_at');

        foreach ($projectCollection as $project) {
            $projectCollectionTemp->add($project);
        }

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

    public function getNewUserProjects()
    {
        if (Auth::user()->id == 469 || Auth::user()->id == 470) {
            return view('rmto-preview.pages.management.user-projects-list-admin');
        } else {
            return view('rmto-preview.pages.management.user-projects-list-new');
        }
    }

    public function getProvinceProjectsItemPublic(Request  $request)
    {
        $request->validate([
            'start-date' => 'date_format:Y-m-d',
            'end-date' => 'date_format:Y-m-d'
        ]);

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

        $province = \App\Models\Province::find(9);
        $roadItemsProjects = $province->roadItemsProjects()
            ->where('road_items_projects.item', '<', '17')
            ->whereBetween('road_items_projects.created_at', [$startDate, $endtDate])
            ->get();
        $roadPatrolProjects = $province->roadPatrolProjects()
            ->whereBetween('road_patrol_projects.created_at', [$startDate, $endtDate])
            ->get();

        $projectCollection = new \Illuminate\Support\Collection();
        $projectCollectionTemp = new \Illuminate\Support\Collection();

        foreach ($roadItemsProjects as $roadItemsProject) {
            if (($roadItemsProject->sub_items != null && $roadItemsProject->sub_items_data != null)
                && sizeof($roadItemsProject->sub_items) > 0) {
                $dataKeys = array_keys($roadItemsProject->sub_items_data);

                foreach ($roadItemsProject->sub_items as $key => $subItem) {
                    $subItemData = null;

                    if (isset($dataKeys[$key])) {
                        $subItemData = [
                            $dataKeys[$key] => $roadItemsProject->sub_items_data[$dataKeys[$key]]
                        ];
                    }

                    $project = [
                        'id' => $roadItemsProject->id,
                        'user' => $roadItemsProject->user->name,
                        'type' => 'فعالیت روزانه و جاری راهداری',
                        'item' => $roadItemsProject->item,
                        'sub_items' => [$subItem],
                        'sub_items_data' => $subItemData,
                        'created_at_jalali' => verta($roadItemsProject->created_at)->format('Y/m/d - H:i'),
                        'created_at' => $roadItemsProject->created_at->toDateTimeString(),
                        'can_delete' => 0
                    ];

                    $projectCollection->add($project);
                }
            } else {
                $project = [
                    'id' => $roadItemsProject->id,
                    'user' => $roadItemsProject->user->name,
                    'type' => 'فعالیت روزانه و جاری راهداری',
                    'item' => $roadItemsProject->item,
                    'sub_items' => $roadItemsProject->sub_items,
                    'sub_items_data' => $roadItemsProject->sub_items_data,
                    'created_at_jalali' => verta($roadItemsProject->created_at)->format('Y/m/d - H:i'),
                    'created_at' => $roadItemsProject->created_at->toDateTimeString(),
                    'can_delete' => 0
                ];

                $projectCollection->add($project);
            }
        }

        foreach ($roadPatrolProjects as $roadPatrolProject) {
            $subProjects = $roadPatrolProject->roadPatrolSubProjects()
                ->where('item', '<', '17')->get();

            $subItems = [];

            foreach ($subProjects as $key => $subProject) {
                $subItems[$key] = [
                    'item' => $subProject->item,
                    'sub_items' => $subProject->sub_items,
                    'sub_items_data' => $subProject->sub_items_data
                ];
            }

            $project = [
                'id' => $roadPatrolProject->id,
                'user' => $roadPatrolProject->user->name,
                'type' => 'گشت راهداری و ترابری',
                'created_at_jalali' => verta($roadPatrolProject->created_at)->format('Y/m/d - H:i'),
                'created_at' => $roadPatrolProject->created_at->toDateTimeString(),
                'sub_projects' => $subItems,
                'can_delete' => 1
            ];

            $projectCollection->add($project);
        }

        $projectCollection = $projectCollection->sortByDesc('created_at');

        foreach ($projectCollection as $project) {
            $projectCollectionTemp->add($project);
        }

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

    public function deleteSpecificUserProject(Request  $request)
    {
        $request->validate([
            'id' => 'required|integer',
            'type' => 'required|string|in:ri,rp'
        ]);

        if ($request->input('type') == 'ri') {
            $project = \App\Models\RoadItemsProject::find($request->input('id'));

            $project->files()->delete();
            $project->delete();
        } else {
            $project = \App\Models\RoadPatrolProject::find($request->input('id'));
            $subProjects = $project->roadPatrolSubProjects;

            foreach ($subProjects as $subProject) {
                $subProject->files()->delete();
                $subProject->delete();
            }

            $project->delete();
        }

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

    public function getAdminProvinceProjectsCount(Request  $request)
    {
        $request->validate([
            'start-date' => 'date_format:Y-m-d',
            'end-date' => 'date_format:Y-m-d'
        ]);

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

        $provinces = \App\Models\Province::all();

        $projectsCount = [];
        $countIndex = 0;

        $roadItemsCount = 0;
        $roadPatrolCount = 0;
        $roadConstructionCount = 0;
        $fastReaction = 0;
        $provinceProjectsCount = 0;

        foreach ($provinces as $province) {
            $projectsCount[$countIndex]['province_id'] = $province->id;
            $projectsCount[$countIndex]['province_name'] = $province->name_fa;
            $projectsCount[$countIndex]['roadItemsProjects'] = $province->roadItemsProjects()
                ->where('item', '<', '17')
                ->whereBetween('road_items_projects.created_at', [$startDate, $endtDate])->count();
            $roadPatrolProjects = $province->roadPatrolProjects()
                ->whereBetween('road_patrol_projects.created_at', [$startDate, $endtDate])->get();
            $projectsCount[$countIndex]['roadPatrolProjects'] = $roadPatrolProjects->count();

            $projectsCount[$countIndex]['roadPatrolSubProjects'] = 0;

            foreach ($roadPatrolProjects as $roadPatrolProject) {
                $projectsCount[$countIndex]['roadPatrolSubProjects'] += $roadPatrolProject->roadPatrolSubProjects()
                    ->where('item', '<', '17')->count();
            }

            $projectsCount[$countIndex]['roadConstructionProjects'] = $province->roadConstructionProjects()
                ->whereBetween('road_construction_projects.created_at', [$startDate, $endtDate])->count();

            $projectsCount[$countIndex]['fastReaction'] = $province->fastReactionProjects()
                ->where('road_observeds.rms_status', 1)
                ->whereBetween('road_observeds.created_at', [$startDate, $endtDate])->count();

            $projectsCount[$countIndex]['projectsCount'] = $projectsCount[$countIndex]['roadItemsProjects']
                + $projectsCount[$countIndex]['roadPatrolProjects']
                + $projectsCount[$countIndex]['roadConstructionProjects']
                + $projectsCount[$countIndex]['fastReaction'];

            $roadItemsCount += $projectsCount[$countIndex]['roadItemsProjects'];
            $roadPatrolCount += $projectsCount[$countIndex]['roadPatrolProjects'];
            $roadConstructionCount += $projectsCount[$countIndex]['roadConstructionProjects'];
            $fastReaction += $projectsCount[$countIndex]['fastReaction'];
            $provinceProjectsCount += $projectsCount[$countIndex]['projectsCount'];

            $countIndex++;
        }

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => [
                'projects' => $projectsCount,
                'count' => [
                    'roadItemsCount' => $roadItemsCount,
                    'roadPatrolCount' => $roadPatrolCount,
                    'roadConstructionCount' => $roadConstructionCount,
                    'fastReaction' => $fastReaction,
                    'totalCount' => $provinceProjectsCount
                ]
            ]
        ], 200);
    }

    public function getAdminCityProjectsCount(Request  $request)
    {
        $request->validate([
            'province-id' => 'required|integer',
            'start-date' => 'date_format:Y-m-d',
            'end-date' => 'date_format:Y-m-d'
        ]);

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

        $cities = User::where('province_id', $request->input('province-id'))
            ->whereNotBetween('id', [466, 470])
            ->get();

        $projectsCount = [];
        $countIndex = 0;

        $roadItemsCount = 0;
        $roadPatrolCount = 0;
        $roadConstructionCount = 0;
        $cityProjectsCount = 0;

        foreach ($cities as $city) {
            $projectsCount[$countIndex]['province_id'] = $city->province->id;
            $projectsCount[$countIndex]['province_name'] = $city->province->name_fa;
            $projectsCount[$countIndex]['city_id'] = $city->id;
            $projectsCount[$countIndex]['city_name'] = $city->name;
            $projectsCount[$countIndex]['roadItemsProjects'] = $city->roadItemsProjects()
                ->where('item', '<', '17')
                ->whereBetween('road_items_projects.created_at', [$startDate, $endtDate])->count();
            $roadPatrolProjects = $city->roadPatrolProjects()
                ->whereBetween('road_patrol_projects.created_at', [$startDate, $endtDate])->get();
            $projectsCount[$countIndex]['roadPatrolProjects'] = $roadPatrolProjects->count();

            $projectsCount[$countIndex]['roadPatrolSubProjects'] = 0;

            foreach ($roadPatrolProjects as $roadPatrolProject) {
                $projectsCount[$countIndex]['roadPatrolSubProjects'] += $roadPatrolProject->roadPatrolSubProjects()
                    ->where('item', '<', '17')->count();
            }

            $projectsCount[$countIndex]['roadConstructionProjects'] = $city->roadConstructionProjects()
                ->whereBetween('road_construction_projects.created_at', [$startDate, $endtDate])->count();

            $projectsCount[$countIndex]['projectsCount'] = $projectsCount[$countIndex]['roadItemsProjects']
                + $projectsCount[$countIndex]['roadPatrolProjects']
                + $projectsCount[$countIndex]['roadConstructionProjects'];

            $roadItemsCount += $projectsCount[$countIndex]['roadItemsProjects'];
            $roadPatrolCount += $projectsCount[$countIndex]['roadPatrolProjects'];
            $roadConstructionCount += $projectsCount[$countIndex]['roadConstructionProjects'];
            $cityProjectsCount += $projectsCount[$countIndex]['projectsCount'];

            $countIndex++;
        }

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => [
                'projects' => $projectsCount,
                'count' => [
                    'roadItemsCount' => $roadItemsCount,
                    'roadPatrolCount' => $roadPatrolCount,
                    'roadConstructionCount' => $roadConstructionCount,
                    'totalCount' => $cityProjectsCount
                ]
            ]
        ], 200);
    }

    public function getProfileAndUserList()
    {
        $authUser = Auth::user();
        $users = null;
        $usersArray = [];

        if ($authUser->id == 470) {                         // witel
            $users = User::whereNotIn('id', [470])
                ->get();
        } elseif ($authUser->id == 469) {                   // danesh
            $users = User::whereNotIn('id', [466, 469, 470])
                ->get();
        } elseif ($authUser->id <= 35) {
            $users = User::where('province_id', $authUser->province_id)
                ->where('id', '>', 35)
                ->whereNotBetween('id', [466, 470])
                ->get();
        } else {
            //
        }

        $usersArray[0] = [
            'id' => $authUser->id,
            'provinceName' => ($authUser->province_id) ? $authUser->province->name_fa : '-',
            'name' => $authUser->name,
            'username' => $authUser->username,
            'password' => '-',
            'firstName' => $authUser->first_name ?? '-',
            'lastName' => $authUser->last_name ?? '-',
            'mobile' => $authUser->mobile ?? '-',
            'lastSubmit' => '-',
            'status' => '-',
            'degree' => $authUser->degree ?? '-',
            'photo' => (($authUser->photo) ?
                asset('storage' . substr($authUser->photo, 6)) :
                'https://rms.rmto.ir/storage/no-image-1.jpg'),
            'delete' => 0
        ];

        foreach ($users as $key => $user) {
            $usersArray[$key + 1] = [
                'id' => $user->id,
                'provinceName' => ($user->province_id) ? $user->province->name_fa : '-',
                'name' => $user->name,
                'username' => $user->username,
                'password' => '-',
                'firstName' => $user->first_name ?? '-',
                'lastName' => $user->last_name ?? '-',
                'mobile' => $user->mobile ?? '-',
                'lastSubmit' => '-',
                'status' => '-',
                'degree' => $user->degree ?? '-',
                'photo' => (($user->photo) ?
                    asset('storage' . substr($user->photo, 6)) :
                    'https://rms.rmto.ir/storage/no-image-1.jpg'),
                'delete' => 1
            ];
        }

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

    public function getProfileAndUserListPublic()
    {
        $authUser = User::find(470);
        $users = null;
        $usersArray = [];

        if ($authUser->id == 470) {                             // witel
            $users = User::whereNotIn('id', [470])
                ->get();
        } elseif ($authUser->id == 469) {                       // danesh
            $users = User::whereNotIn('id', [466, 469, 470])
                ->get();
        } elseif ($authUser->id <= 35) {
            $users = User::where('province_id', $authUser->province_id)
                ->where('id', '>', 35)
                ->whereNotBetween('id', [466, 470])
                ->get();
        } else {
            //
        }

        $usersArray[0] = [
            'id' => $authUser->id,
            'provinceName' => ($authUser->province_id) ? $authUser->province->name_fa : '-',
            'name' => $authUser->name,
            'username' => $authUser->username,
            'password' => '-',
            'firstName' => $authUser->first_name ?? '-',
            'lastName' => $authUser->last_name ?? '-',
            'mobile' => $authUser->mobile ?? '-',
            'lastSubmit' => '-',
            'status' => '-',
            'degree' => $authUser->degree ?? '-',
            'photo' => (($authUser->photo) ?
                    asset('storage' . substr($authUser->photo, 6)) :
                    'https://rms.rmto.ir/storage/no-image-1.jpg'),
            'delete' => 0
        ];

        foreach ($users as $key => $user) {
            $usersArray[$key + 1] = [
                'id' => $user->id,
                'provinceName' => ($user->province_id) ? $user->province->name_fa : '-',
                'name' => $user->name,
                'username' => $user->username,
                'password' => '-',
                'firstName' => $user->first_name ?? '-',
                'lastName' => $user->last_name ?? '-',
                'mobile' => $user->mobile ?? '-',
                'lastSubmit' => '-',
                'status' => '-',
                'degree' => $user->degree ?? '-',
                'photo' => (($user->photo) ?
                    asset('storage' . substr($user->photo, 6)) :
                    'https://rms.rmto.ir/storage/no-image-1.jpg'),
                'delete' => 1
            ];
        }

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

    public function getUserListPage()
    {
        return view('rmto-preview.pages.management.user-list-new');
    }

    public function updateUserInfo(Request $request, $id)
    {
        $request->validate([
            'name' => 'string',
            'username' => 'string|unique:users,username',
            'fname' => 'string',
            'lname' => 'string',
            'mobile' => 'digits:11|regex:/^09[0-9]{9}$/i',
            'degree' => 'string',
            'image' => 'image',
            'password' => 'string|min:8|confirmed|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$/'
        ]);

        $user = User::find($id);

        $user->name = $request->input('name') ?? $user->name;
        $user->username = $request->input('username') ?? $user->username;
        $user->first_name = $request->input('fname') ?? $user->first_name;
        $user->last_name = $request->input('lname') ?? $user->last_name;
        $user->mobile = $request->input('mobile') ?? $user->mobile;
        $user->degree = $request->input('degree') ?? $user->degree;
        if ($request->file('image')) {
            $user->photo = $request->file('image')->store('public/users/photo');
        }
        if ($request->input('password')) {
            $user->password = Hash::make($request->input('password'));
        }

        //$user->save();

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

    public function getRoadItemsProjectsStat(Request  $request)
    {
        $request->validate([
            'start-date' => 'date_format:Y-m-d',
            'end-date' => 'date_format:Y-m-d'
        ]);

        if ($request->input('start-date') && $request->input('end-date')) {
            $startDate = date($request->input('start-date') . ' 00:00:00');
            $endtDate = date($request->input('end-date') . ' 23:59:59');
        } else {
            $startDate = date('Y-m-d 00:00:00');
            $endtDate = date('Y-m-d H:i:s');
        }
        //// if role admin in code
        if (Auth::user()->username == 'witel' || Auth::user()->username == 'drdanesh') {
            $roadItemsProjects = \App\Models\RoadItemsProject::whereBetween('created_at', [$startDate, $endtDate])
                ->get();
        } else {
            ////  else  in code
            $roadItemsProjects = \App\Models\RoadItemsProject::where('province_id', Auth::user()->province_id)
                ->whereBetween('created_at', [$startDate, $endtDate])
                ->get();
        }

        $subItems = [];
        $subItems['project'] = $roadItemsProjects->count();

        foreach ($roadItemsProjects as $project) {
            if (isset($subItems['item_' . $project->item]) && $subItems['item_' . $project->item] > 0) {
                $subItems['item_' . $project->item]++;
            } else {
                $subItems['item_' . $project->item] = 1;
            }
        }

        for ($i = 1; $i < 18; $i++) {
            if (!isset($subItems['item_' . $i])) {
                $subItems['item_' . $i] = 0;
            }
        }

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

    public function getAdminProvinceProjectsItem(Request  $request, $id)
    {
        $request->validate([
            'start-date' => 'date_format:Y-m-d',
            'end-date' => 'date_format:Y-m-d'
        ]);

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

        $province = \App\Models\Province::find($id);
        ///// if role admin kole in code
        if (Auth::user()->username == 'witel' || Auth::user()->username == 'drdanesh') {
            $roadItemsProjects = $province->roadItemsProjects()
                ->whereBetween('road_items_projects.created_at', [$startDate, $endtDate])
                ->get();
            $roadPatrolProjects = $province->roadPatrolProjects()
                ->whereBetween('road_patrol_projects.created_at', [$startDate, $endtDate])
                ->get();
            $fastReactionProjects = $province->fastReactionProjects()
                ->where('road_observeds.rms_status', 1)
                ->whereBetween('road_observeds.created_at', [$startDate, $endtDate])
                ->get();
        } else {
            //// else in code
            $roadItemsProjects = $province->roadItemsProjects()
                ->where('province_id', $id)
                ->whereBetween('road_items_projects.created_at', [$startDate, $endtDate])
                ->get();
            $roadPatrolProjects = $province->roadPatrolProjects()
                ->where('province_id', $id)
                ->whereBetween('road_patrol_projects.created_at', [$startDate, $endtDate])
                ->get();
            $fastReactionProjects = $province->fastReactionProjects()
                ->where('rms_province_id', $id)
                ->where('road_observeds.rms_status', 1)
                ->whereBetween('road_observeds.created_at', [$startDate, $endtDate])
                ->get();
        }
        $projectCollection = new \Illuminate\Support\Collection();
        $projectCollectionTemp = new \Illuminate\Support\Collection();

        foreach ($roadItemsProjects as $roadItemsProject) {
            if ($roadItemsProject->user->username == 'witel' || $roadItemsProject->user->username == 'drdanesh') {
                continue;
            }

            $canDelete = 1;

            if (($roadItemsProject->sub_items != null && $roadItemsProject->sub_items_data != null)
                && sizeof($roadItemsProject->sub_items) > 0) {
                $dataKeys = array_keys($roadItemsProject->sub_items_data);

                foreach ($roadItemsProject->sub_items as $key => $subItem) {
                    $subItemData = null;

                    if (isset($dataKeys[$key])) {
                        $subItemData = [
                            $dataKeys[$key] => $roadItemsProject->sub_items_data[$dataKeys[$key]]
                        ];
                    }

                    $project = [
                        'id' => $roadItemsProject->id,
                        'user' => $roadItemsProject->user->name,
                        'type' => 'فعالیت روزانه و جاری راهداری',
                        'item' => $roadItemsProject->item,
                        'sub_items' => [$subItem],
                        'sub_items_data' => $subItemData,
                        'created_at_jalali' => verta($roadItemsProject->created_at)->format('Y/m/d - H:i'),
                        'created_at' => $roadItemsProject->created_at->toDateTimeString(),
                        'can_delete' => $canDelete
                    ];

                    $projectCollection->add($project);
                }
            } else {
                $project = [
                    'id' => $roadItemsProject->id,
                    'user' => $roadItemsProject->user->name,
                    'type' => 'فعالیت روزانه و جاری راهداری',
                    'item' => $roadItemsProject->item,
                    'sub_items' => $roadItemsProject->sub_items,
                    'sub_items_data' => $roadItemsProject->sub_items_data,
                    'created_at_jalali' => verta($roadItemsProject->created_at)->format('Y/m/d - H:i'),
                    'created_at' => $roadItemsProject->created_at->toDateTimeString(),
                    'can_delete' => $canDelete
                ];

                $projectCollection->add($project);
            }
        }

        foreach ($roadPatrolProjects as $roadPatrolProject) {
            if ($roadPatrolProject->user->username == 'witel' || $roadPatrolProject->user->username == 'drdanesh') {
                continue;
            }

            $subProjects = $roadPatrolProject->roadPatrolSubProjects()
                ->where('item', '<', '22')->get();

            $subItems = [];

            foreach ($subProjects as $key => $subProject) {
                $subItems[$key] = [
                    'item' => $subProject->item,
                    'sub_items' => $subProject->sub_items,
                    'sub_items_data' => $subProject->sub_items_data
                ];
            }

            $canDelete = 1;

            $project = [
                'id' => $roadPatrolProject->id,
                'user' => $roadPatrolProject->user->name,
                'type' => 'گشت راهداری و ترابری',
                'created_at_jalali' => verta($roadPatrolProject->created_at)->format('Y/m/d - H:i'),
                'created_at' => $roadPatrolProject->created_at->toDateTimeString(),
                'sub_projects' => $subItems,
                'can_delete' => $canDelete
            ];
            $projectCollection->add($project);
        }

        foreach ($fastReactionProjects as $fastReactionProject) {
            $project = [
                'id' => $fastReactionProject->id,
                'user' => 'شهرستان ' . $fastReactionProject->TownName,
                'type' => 'واکنش سریع',
                'created_at_jalali' => verta($fastReactionProject->created_at)->format('Y/m/d - H:i'),
                'created_at' => $fastReactionProject->created_at->toDateTimeString(),
                'can_delete' => 0
            ];
            $projectCollection->add($project);
        }

        $projectCollection = $projectCollection->sortByDesc('created_at');

        foreach ($projectCollection as $project) {
            $projectCollectionTemp->add($project);
        }

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

    public function get_city_items(Request $request)
    {
        // $user = Auth::user();
        // $id = $user->id;
        $id = 1;
        $p_p = 7;
        if ($request->input('date-from') and $request->input('date-to')) {
            $date_from = new Verta($request->input('date-from'));
            $date_to = new Verta($request->input('date-to'));
            $date_bool = 1;
        } else {
            $date_from = date("Y-m-d");
            $date_from .=' 00:00:01';
            $date_to = date("Y-m-d H:i:s");
            $date_bool = 1;
        }
        ////// check for admin
        if ($id == 469 || $id == 470) {
            echo 'nothing';
            $province = $request->input('province-id');
        } else {
            // $p_p = $user->province_id;
            $itemss = DB::table('road_items_projects')
                        ->when($date_from != null and $date_to != null, function ($query) use ($date_from, $date_to) {
                            return $query->whereBetween('road_items_projects.created_at', [$date_from, $date_to]);
                        })
                        ->when(!empty($p_p), function ($query) use ($p_p) {
                            return $query->where('users.province_id', '>', $p_p);
                        })
                        ->leftJoin('users', 'users.id', '=', 'road_items_projects.user_id')
                        ->leftJoin('cities', 'cities.id', '=', 'users.city_id')
                        ->where('city_id', '>', 0)
                        ->select('count(*) as count, item, city_id, name_fa')
                        ->groupBy('city_id', 'item')
                        ->get();
            // $items_array = $itemss->toArray();
            $counts = array();
            $lastkey = null;
            // return $itemss;
            $tmp = null;
            // $counts['count_all'] = 0;
            $count_all = 0;
            foreach ($itemss as $key => $value) {
                if ($key > 0) {
                    if ($value->city_id == $counts[$lastkey]['city_id']) {
                        $counts[$lastkey]['items'] += [$value->item => $value->count];
                        $counts[$lastkey]['count_items'] += $value->count;
                        $count_all += $value->count;
                        continue;
                    }
                }
                $counts[$key] = [
                    'city_id' => $value->city_id,
                    'city_na' => $value->name_fa,
                    'items' => [
                        $value->item => $value->count
                    ],
                        'count_items' => $value->count
                    ];
                $count_all += $value->count;
                $lastkey = $key;
            }
            // $tmp['count_all'] = $counts['count_all'];
            // unset($counts['count_all']);
            // return $tmp;
            $tmp = array_values($counts);
            return response()->json([
                'status' => 'succeed',
                'message' => '',
                'data' => $tmp,
                'count_all' => $count_all
            ], 200);
        }
    }

    public function getAdminProjectItems(Request $request)
    {
        $provinceID = $request->province_id ?? null;

        $request->validate([
            'start-date' => 'date_format:Y-m-d',
            'end-date' => 'date_format:Y-m-d'
        ]);

        if ($request->input('start-date') && $request->input('end-date')) {
            $startDate = date($request->input('start-date') . ' 00:00:00');
            $endtDate = date($request->input('end-date') . ' 23:59:59');
        } else {
            $startDate = date('Y-m-d 00:00:00');
            $endtDate = date('Y-m-d H:i:s');
        }
        if (Auth::user()->username == 'witel' || Auth::user()->username == 'drdanesh') {
            $roadItemsProjects = \App\Models\RoadItemsProject::whereBetween('road_items_projects.created_at', [$startDate, $endtDate])
                ->when($provinceID, function ($query, $provinceID) {
                    return $query->where('province_id', $provinceID);
                })
                ->get();
            $roadPatrolProjects = \App\Models\RoadPatrolProject::whereBetween('road_patrol_projects.created_at', [$startDate, $endtDate])
                ->when($provinceID, function ($query, $provinceID) {
                    return $query->where('province_id', $provinceID);
                })
                ->get();
            $fastReactionProjects = \App\Models\RoadObserved::where('road_observeds.rms_status', 1)
                ->whereBetween('road_observeds.created_at', [$startDate, $endtDate])
                ->when($provinceID, function ($query, $provinceID) {
                    return $query->where('rms_province_id', $provinceID);
                })
                ->get();
        } else {
            $roadItemsProjects = \App\Models\RoadItemsProject::whereBetween('road_items_projects.created_at', [$startDate, $endtDate])
                ->where('province_id', Auth::user()->province_id)
                ->get();
            $roadPatrolProjects = \App\Models\RoadPatrolProject::whereBetween('road_patrol_projects.created_at', [$startDate, $endtDate])
            ->where('province_id', Auth::user()->province_id)
                ->get();
            $fastReactionProjects = \App\Models\RoadObserved::where('road_observeds.rms_status', 1)
                ->whereBetween('road_observeds.created_at', [$startDate, $endtDate])
                ->where('rms_province_id', Auth::user()->province_id)
                ->get();
        }
        $projectCollection = new \Illuminate\Support\Collection();
        $projectCollectionTemp = new \Illuminate\Support\Collection();

        foreach ($roadItemsProjects as $roadItemsProject) {
            if ($roadItemsProject->user->username == 'witel' || $roadItemsProject->user->username == 'drdanesh') {
                continue;
            }

            $canDelete = 1;

            if (($roadItemsProject->sub_items != null && $roadItemsProject->sub_items_data != null)
                && sizeof($roadItemsProject->sub_items) > 0) {
                $dataKeys = array_keys($roadItemsProject->sub_items_data);

                foreach ($roadItemsProject->sub_items as $key => $subItem) {
                    $subItemData = null;

                    if (isset($dataKeys[$key])) {
                        $subItemData = [
                            $dataKeys[$key] => $roadItemsProject->sub_items_data[$dataKeys[$key]]
                        ];
                    }

                    $project = [
                        'id' => $roadItemsProject->id,
                        'user' => $roadItemsProject->user->name,
                        'province' => $roadItemsProject->user->province_fa,
                        'type' => 'فعالیت روزانه و جاری راهداری',
                        'item' => $roadItemsProject->item,
                        'sub_items' => [$subItem],
                        'sub_items_data' => $subItemData,
                        'created_at_jalali' => verta($roadItemsProject->created_at)->format('Y/m/d - H:i'),
                        'created_at' => $roadItemsProject->created_at->toDateTimeString(),
                        'can_delete' => $canDelete
                    ];

                    $projectCollection->add($project);
                }
            } else {
                $project = [
                    'id' => $roadItemsProject->id,
                    'user' => $roadItemsProject->user->name,
                    'province' => $roadItemsProject->user->province_fa,
                    'type' => 'فعالیت روزانه و جاری راهداری',
                    'item' => $roadItemsProject->item,
                    'sub_items' => $roadItemsProject->sub_items,
                    'sub_items_data' => $roadItemsProject->sub_items_data,
                    'created_at_jalali' => verta($roadItemsProject->created_at)->format('Y/m/d - H:i'),
                    'created_at' => $roadItemsProject->created_at->toDateTimeString(),
                    'can_delete' => $canDelete
                ];

                $projectCollection->add($project);
            }
        }

        foreach ($roadPatrolProjects as $roadPatrolProject) {
            if ($roadPatrolProject->user->username == 'witel' || $roadPatrolProject->user->username == 'drdanesh') {
                continue;
            }

            $subProjects = $roadPatrolProject->roadPatrolSubProjects()
                ->get();

            $subItems = [];

            foreach ($subProjects as $key => $subProject) {
                $subItems[$key] = [
                    'item' => $subProject->item,
                    'sub_items' => $subProject->sub_items,
                    'sub_items_data' => $subProject->sub_items_data
                ];
            }

            $canDelete = 1;

            $project = [
                'id' => $roadPatrolProject->id,
                'user' => $roadPatrolProject->user->name,
                'province' => $roadPatrolProject->user->province_fa,
                'type' => 'گشت راهداری و ترابری',
                'created_at_jalali' => verta($roadPatrolProject->created_at)->format('Y/m/d - H:i'),
                'created_at' => $roadPatrolProject->created_at->toDateTimeString(),
                'sub_projects' => $subItems,
                'can_delete' => $canDelete
            ];
            $projectCollection->add($project);
        }

        foreach ($fastReactionProjects as $fastReactionProject) {
            $project = [
                'id' => $fastReactionProject->id,
                'user' => 'شهرستان ' . $fastReactionProject->TownName,
                'province' => $fastReactionProject->ProvinceName,
                'type' => 'واکنش سریع',
                'created_at_jalali' => verta($fastReactionProject->created_at)->format('Y/m/d - H:i'),
                'created_at' => $fastReactionProject->created_at->toDateTimeString(),
                'can_delete' => 0
            ];
            $projectCollection->add($project);
        }

        $projectCollection = $projectCollection->sortByDesc('created_at');

        foreach ($projectCollection as $project) {
            $projectCollectionTemp->add($project);
        }

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

    public function changeConfirmedStatus(Request $request)
    {
        $request->validate([
            'user_ids' => 'required|regex:/^(\d+)(,\d+)*$/',
            'confirm' => 'required|in:0,1'
        ]);

        $user_ids = explode(",", $request->user_ids);

        User::whereIn('id', $user_ids)->update([
            'confirmed' => $request->confirm
        ]);
        return response()->json([
            'status' => 'succeed',
        ]);
    }

    public function givePermissionsTo(Request $request)
    {
        $request->validate([
            'user_ids' => 'required|regex:/^(\d+)(,\d+)*$/',
            'permission_ids' => 'required',
        ]);

        $user_ids = explode(",", $request->user_ids);
        $permission_ids = $request->permission_ids;

        User::whereIn('id', $user_ids)->get()->each(function ($user) use ($permission_ids) {
            $user->syncPermissions($permission_ids);
        });

        return response()->json([
            'status' => 'succeed',
            'message' => 'permissions assigned to users succussfully.'
        ]);
    }

    public function destroy(Request $request)
    {
        $request->validate([
            'user_ids' => 'required|regex:/^(\d+)(,\d+)*$/',
        ]);

        $user_ids = explode(',', $request->user_ids);

        foreach ($user_ids as $id) {
            $user = User::find($id);

            if ($user->avatar) {
                if (Storage::disk('public')->exists(str_replace('storage/', '', $user->avatar))) {
                    Storage::disk('public')->delete(str_replace('storage/', '', $user->avatar));
                }
            }

            if ($user->photo) {
                if (Storage::disk('public')->exists(str_replace('storage/', '', $user->photo))) {
                    Storage::disk('public')->delete(str_replace('storage/', '', $user->photo));
                }
            }

            $user->delete();
        }

        return response()->json([
            'status' => 200,
            'message' => 'The users deleted succussfully.'
        ]);
    }

    public function getUserPermissionsTypes()
    {
        $auth_user_permissions_types = auth()->user()->permissions()->groupBy('type')->pluck('type')->toArray();

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

    public function getUserPermissions()
    {
        $userPermissions = Auth::user()->getUserPermissions();

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

    public function getUserSummaryReport(Request $request, User $user)
    {
        $request->fromDate = $request->fromDate ? $request->fromDate . " 00:00:00" : Carbon::now()->subDays(30)->format('Y-m-d 00:00:00');
        $request->toDate = $request->toDate ? $request->toDate . " 23:59:59" : Carbon::now()->format('Y-m-d 23:59:59');
        $data = [];

        $ids_list = '';
        $temp_sql_for_activity_time = "
        SELECT sum(majmoe) AS activity FROM (SELECT *,
        COUNT(cnt) AS majmoe
        FROM (
                SELECT *,
                    COUNT(*) AS cnt
                FROM (
                        SELECT YEAR (created_at) AS yy,
                            MONTH (created_at) AS mm,
                            DAY (created_at) AS dd,
                            HOUR (created_at) AS hh,
                            user_id
                        FROM user_activity_logs
                        WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(".$user->id.")
                    ) user_activity_distinct
                GROUP BY yy,
                    mm,
                    dd,
                    hh,
                    user_id
            ) user_activity_by_hour_and_
        GROUP BY user_id) AS calculated_table;";

        $temp_sql_for_activity_list = "
                SELECT *,
                    COUNT(*) AS cnt
                FROM (
                        SELECT 
                            description,
                            log_unique_code
                        FROM user_activity_logs
                        WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(".$user->id.")
                    ) user_activity_distinct
                GROUP BY
                    log_unique_code
                ORDER BY  cnt desc";

        $number_of_active_days = "
                SELECT COUNT(*) AS cnt
                FROM (
                        SELECT mm,dd
                        FROM user_activity_logs
                        WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(".$user->id.")
                        GROUP BY
                    mm,dd
                    ) active_days
                ORDER BY  cnt desc";


        $number_of_activities = "
        SELECT COUNT(*) AS cnt
                FROM user_activity_logs
                WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(".$user->id.")
        ORDER BY  cnt desc";

        $number_of_active_days = (DB::select($number_of_active_days)[0]->cnt ? DB::select($number_of_active_days)[0]->cnt : -1);
        $activity_time = DB::select($temp_sql_for_activity_time)[0]->activity;
        $number_of_activities = DB::select($number_of_activities)[0]->cnt;
        $data = [
            'number_of_active_days' => $number_of_active_days,

            'activity_time' => $user->id ? $activity_time : null,
            'average_activity_time' => round(($user->id ? $activity_time : 0) / $number_of_active_days, 2) ,
            'number_of_activities' => $number_of_activities ,
            'average_activity_number' => round(($user->id ? $number_of_activities : 0) / $number_of_active_days, 2) ,

            'activity_list' => $user->id ? DB::select($temp_sql_for_activity_list) : null,
            'last_login' => $user->last_login,
            ];
        return $data;
    }

    public function changeUserEnabeld(User $user)
    {
        if (Auth::user()->checkUserHasPermission('full-user-management')) {
            $user->enabled = !$user->enabled;
            $user->save();
            return response()->json([
                'message' => 'success'
            ], 200);
        } elseif (Auth::user()->checkUserHasPermission('limited-user-management') && Auth::user()->province_id == $user->province_id) {
            $user->enabled = !$user->enabled;
            $user->save();
            return response()->json([
                'message' => 'success'
            ], 200);
        } else {
            return response()->json([
                'message' => 'Forbidden'
            ], 403);
        }
    }

    public function deleteRole(Request $request, $id)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1045);
        }
        $role = Role::find($id)->delete();

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

    public function getAllPermissions()
    {
        $permissions = Permission::select('id', 'name', 'name_fa', 'description', 'type', 'need_province', 'need_edare_shahri', 'type_fa')
                                    ->orderBy('type')
                                    // ->where('id', '>', 9)
                                    ->get();

        return response()->json([
            'Permissions' => $permissions,
        ]);
    }

    public function userPermission($id)
    {
        $user = User::find($id);
        return response()->json([
            'message' => 'success',
            'data' => $user->permissions,
        ]);
    }

    public function assignPermission(Request $request, User $user)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1042);
        }
        $permissions = explode(",", $request->permissions);
        if (! $permissions == null) {
            $user->syncPermissions($permissions);
        }

        return response()->json([
            'message' => 'status',
            'data' => User::where('id', $user->id)->with(['permissions'])->get()
        ]);
    }

    public function createRole(Request $request)
    {
        $request->validate([
            'role_name' => 'required|string',
            'permissions' => 'required'
        ], [
            'permissions.required' => 'انتخاب دسترسی‌ها الزامی است.',
            'role_name.required' => 'نام نقش الزامی است.'
        ]);

        if (auth()->user()) {
            auth()->user()->addActivityComplete(1043);
        }

        $role = Role::create([
            'name' => time(),
            'name_fa' => $request->role_name,
            'description' => $request->description
        ]);

        $permissions = $request->permissions;

        // $permissions = explode(",", $request->permissions);
        $role->givePermissionTo($permissions);

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

    public function showAllRoles(Request $request)
    {
        $roles = Role::where('for_report', 0)->get();

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

    public function showRole($id, Request $request)
    {
        $role = Role::where('id', $id)->with('permissions:id,name,name_fa,description')->first();

        return response()->json([
            'message' => 'success',
            'data' => [
                'role' => Role::whereId($id)->first(),
                'permissions' => $role->permissions
            ]
        ]);
    }

    public function editRole(Request $request, $id)
    {
        $request->validate([
            'role_name' => 'required|string',
            'permissions' => 'required'
        ], [
            'permissions.required' => 'انتخاب دسترسی‌ها الزامی است.',
            'role_name.required' => 'نام نقش الزامی است.'
        ]);

        if (auth()->user()) {
            auth()->user()->addActivityComplete(1044);
        }
        $role = Role::find($id);


        $updateRole = $role->update([
            'name_fa' => $request->role_name,
            'description' => $request->description
        ]);

        $permissions = $request->permissions;
        // $permissions = explode(",", $request->permissions);

        $role->syncPermissions($permissions);

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

    // public function profile()
    // {
    //     return response()->json([
    //         'message' => 'success',
    //         'data' => Auth::user()->get()
    //     ]);
    // }

    public function profile_edit(Request $request)
    {
        $user = Auth::user();

        $validData = $request->validate([
            'first_name' => 'required',
            'last_name' => 'required',
            'degree' => 'required',
            'major' => 'required',
            'mobile' => 'required',
        ]);

        $user->first_name = $request->first_name;
        $user->last_name = $request->last_name;
        $user->degree = $request->degree;
        $user->major = $request->major;
        if (!is_null($request->password)) {
            $user->password = Hash::make($request->password);
        }
        $user->mobile = $request->mobile;
        $user->save();

        if ($request->has('avatar')) {
            File::delete($user->avatar);
            $destinationPath = 'avatar/' . $user->username;
            $filename = time() .".". $request->file('avatar')->getClientOriginalExtension();
            $request->file('avatar')->storeAs($destinationPath, $filename, 'public');
            $user->update(['avatar' => 'storage/'.$destinationPath ."/". $filename]);
        }

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

    public function storeInformation(Request $request)
    {
        $user = Auth::user();

        $validData = $request->validate([
            'first_name' => 'required',
            'last_name' => 'required',
            'degree' => 'required',
            'major' => 'required',
            'mobile' => 'required',
            'password' => 'required',
        ]);


        $user->first_name = $request->first_name;
        $user->last_name = $request->last_name;
        $user->degree = $request->degree;
        $user->major = $request->major;
        $user->mobile = $request->mobile;
        $user->password = Hash::make($request->password);
        $user->confirmed = 1;
        $user->save();

        if ($request->has('avatar')) {
            Storage::delete('public/' . $user->avatar);
            $destinationPath = 'avatar/' . $user->username;
            $filename = time() .".". $request->file('avatar')->getClientOriginalExtension();
            $request->file('avatar')->storeAs($destinationPath, $filename, 'public');
            $user->update(['avatar' => 'storage/'.$destinationPath ."/". $filename]);
        }

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

    public function getMyData()
    {
        return response()->json([
            'message' => 'success',
            'data' => Auth::user()
        ]);
    }
}
