<?php

namespace App\Http\Controllers\V3\Dashboard;

use App\Http\Controllers\Controller;
use App\Http\Requests\V3\Dashboard\UserManagement\PermissionUpdateRequest;
use App\Http\Requests\V3\Dashboard\UserManagement\StoreRequest;
use App\Http\Requests\V3\Dashboard\UserManagement\UpdateRequest;
use App\Http\Traits\ApiResponse;
use App\Models\City;
use App\Models\EdarateOstani;
use App\Models\EdarateShahri;
use App\Models\Permission;
use App\Models\Province;
use App\Models\Role;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class UserManagementController extends Controller
{
    use ApiResponse;
//    public function index()
//    {
//        if (Auth::user()->can('full-user-managment') || Auth::user()->can('limited-user-management')) {
//            return view('version2.dashboard_pages.user_management.list');
//        }
//
//        abort(403);
//    }
    public function indexUser(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(StoreRequest $request): jsonResponse
    {
        User::query()->create([
            'username' => $request->username,
            'national_code' => $request->national_code,
            'password' => Hash::make($request->password),
            'province_id' => $request->province_id,
            'edarate_ostani_id' => $request->edarate_ostani_id,
            'city_id' => $request->city_id,
            'edarate_shahri_id' => $request->edarate_shahri_id,
        ]);

        $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 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 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 show(User $user)
    {
        $user = User::where('id', $user->id)->with(['roles', 'permissions'])->get();
        return response()->json([
            'status' => '200',
            'message' => 'success',
            'data' => $user
        ], 200);
    }

    public function update(UpdateRequest $request, User $user): JsonResponse
    {
        $user->update([
            'username' => $request->username,
            'national_code' => $request->national_code,
            'password' => Hash::make($request->password),
            'province_id' => $request->province_id,
            'edarate_ostani_id' => $request->edarate_ostani_id,
            'city_id' => $request->city_id,
            'edarate_shahri_id' => $request->edarate_shahri_id,
        ]);

        $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 activityReport()
    {
        return view('version2.dashboard_pages.user_management.activity_report');
    }

    public function userActivityLogs()
    {
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => auth()->user()->activityLogs,
        ], 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 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 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 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 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 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 showAllRoles(Request $request)
    {
        $roles = Role::where('for_report', 0)->get();

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

    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 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);
        }
    }
}
