<?php

namespace App\Http\Controllers;

use App\Models\RoleMaster;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class RoleMasterController extends Controller
{
    /* ===========================
       LIST / INDEX
    ============================ */
    public function index(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'active_only' => 'nullable|boolean',
                'two_fac_auth' => 'nullable|in:Y,N',
                'search' => 'nullable|string|max:100',
                'sort_by' => 'nullable|in:Role_Id,Role_Name,Role_Prefix,created_at,updated_at',
                'sort_order' => 'nullable|in:asc,desc',
                'per_page' => 'nullable|integer|min:1|max:100'
            ]);


            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }


             $query = RoleMaster::query()
                    ->where('Role_Id', '!=', 1);


            if ($request->has('active_only')) {
                $query->where('Is_Active', $request->boolean('active_only'));
            }


            if ($request->has('two_fac_auth')) {
                $query->where('TwoFacAuth', $request->two_fac_auth);
            }


            if ($request->filled('search')) {
                $query->where('Role_Name', 'like', "%{$request->search}%");
            }


            $query->orderBy(
                $request->get('sort_by', 'Role_Name'),
                $request->get('sort_order', 'asc')
            );


              $perPage = $request->get('per_page', 25);
           $roles = $query->paginate($perPage);


            return response()->json([
                'success' => true,
                'data' => $roles
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }


    /* ===========================
       CREATE
    ============================ */
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'Role_Prefix' => 'required|string|max:10|unique:role_master,Role_Prefix',
                'Role_Name'   => 'required|string|max:50|unique:role_master,Role_Name',
                'TwoFacAuth'  => 'required|in:Y,N',
                'Is_Active'   => 'nullable|boolean'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }

            $role = RoleMaster::create([
                'Role_Prefix' => $request->Role_Prefix,
                'Role_Name'   => $request->Role_Name,
                'TwoFacAuth'  => $request->TwoFacAuth,
                'Is_Active'   => $request->get('Is_Active', 1)
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Role created successfully',
                'data' => $role
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    /* ===========================
       SHOW SINGLE
    ============================ */
    public function show($id)
    {
        try {
            $role = RoleMaster::where('Role_Id', $id)->first();

            if (!$role) {
                return response()->json([
                    'success' => false,
                    'message' => 'Role not found'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $role
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    /* ===========================
       UPDATE
    ============================ */
    public function update(Request $request, $id)
    {
        try {
            $role = RoleMaster::where('Role_Id', $id)->first();

            if (!$role) {
                return response()->json([
                    'success' => false,
                    'message' => 'Role not found'
                ], 404);
            }

            $validator = Validator::make($request->all(), [
                'Role_Prefix' => 'sometimes|required|string|max:10|unique:role_master,Role_Prefix,' . $id . ',Role_Id',
                'Role_Name'   => 'sometimes|required|string|max:50|unique:role_master,Role_Name,' . $id . ',Role_Id',
                'TwoFacAuth'  => 'sometimes|required|in:Y,N',
                'Is_Active'   => 'sometimes|boolean'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }

            $role->update([
                'Role_Prefix' => $request->get('Role_Prefix', $role->Role_Prefix),
                'Role_Name'   => $request->get('Role_Name', $role->Role_Name),
                'TwoFacAuth'  => $request->get('TwoFacAuth', $role->TwoFacAuth),
                'Is_Active'   => $request->get('Is_Active', $role->Is_Active),
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Role updated successfully',
                'data' => $role
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }



 public function getAllRolesList(Request $request)
    {
        try {
            // Validation
            $validator = Validator::make($request->all(), [
                'active_only' => 'nullable|boolean',
                'two_fac_auth' => 'nullable|string|in:Y,N',
                'search' => 'nullable|string|max:100',
                'with_user_count' => 'nullable|boolean',
                'sort_by' => 'nullable|string|in:Role_Id,Role_Name,Role_Prefix,created_at,updated_at',
                'sort_order' => 'nullable|string|in:asc,desc',
            ]);


            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation error',
                    'errors' => $validator->errors()
                ], 422);
            }


              $query = RoleMaster::query()
                    ->where('Role_Id', '!=', 1);


            // Filter by active status
            if ($request->has('active_only')) {
                $query->where('Is_Active', $request->boolean('active_only'));
            }


            // Filter by Two Factor Auth
            if ($request->has('two_fac_auth')) {
                $query->where('TwoFacAuth', $request->two_fac_auth);
            }


            // Search
            if ($request->filled('search')) {
                $query->search($request->search);
            }


            // With user count
            if ($request->boolean('with_user_count')) {
                $query->withUserCount();
            }


            // Sorting
            $sortBy = $request->get('sort_by', 'Role_Name');
            $sortOrder = $request->get('sort_order', 'asc');
            $query->orderBy($sortBy, $sortOrder);


            // ✅ Fetch data (NO PAGINATION)
            $roles = $query->get();


            // Format response
            $roles = $roles->map(function ($role) {
                return [
                    'Role_Id' => $role->Role_Id,
                    'Role_Prefix' => $role->Role_Prefix,
                    'Role_Name' => $role->Role_Name,
                    'Full_Role' => $role->full_role,
                    'TwoFacAuth' => $role->TwoFacAuth,
                    'TwoFacAuth_Text' => $role->two_factor_auth_text,
                    'Is_Active' => $role->Is_Active,
                    'Status_Text' => $role->status_text,
                    'created_at' => $role->created_at,
                    'updated_at' => $role->updated_at,
                ];
            });


            return response()->json([
                'success' => true,
                'message' => 'GMC Gandhinagar - Roles fetched successfully',
                'data' => $roles
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch roles',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }





    /* ===========================
       DELETE
    ============================ */
    public function destroy($id)
    {
        try {
            $role = RoleMaster::where('Role_Id', $id)->first();

            if (!$role) {
                return response()->json([
                    'success' => false,
                    'message' => 'Role not found'
                ], 404);
            }

            $role->delete();

            return response()->json([
                'success' => true,
                'message' => 'Role deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    /* ===========================
       ACTIVATE / DEACTIVATE
    ============================ */
    public function activate($id)
    {
        $role = RoleMaster::where('Role_Id', $id)->firstOrFail();
        $role->update(['Is_Active' => 1]);

        return response()->json([
            'success' => true,
            'message' => 'Role activated'
        ]);
    }

    public function deactivate($id)
    {
        $role = RoleMaster::where('Role_Id', $id)->firstOrFail();
        $role->update(['Is_Active' => 0]);

        return response()->json([
            'success' => true,
            'message' => 'Role deactivated'
        ]);
    }

    /* ===========================
       2FA ON / OFF
    ============================ */
    public function enableTwoFactorAuth($id)
    {
        $role = RoleMaster::where('Role_Id', $id)->firstOrFail();
        $role->update(['TwoFacAuth' => 'Y']);

        return response()->json([
            'success' => true,
            'message' => 'Two factor authentication enabled'
        ]);
    }

    public function disableTwoFactorAuth($id)
    {
        $role = RoleMaster::where('Role_Id', $id)->firstOrFail();
        $role->update(['TwoFacAuth' => 'N']);

        return response()->json([
            'success' => true,
            'message' => 'Two factor authentication disabled'
        ]);
    }


    public function getRolesWithUserCount(Request $request)
    {
        try {
            // Validation for query parameters
            $validator = Validator::make($request->all(), [
                'active_only' => 'nullable|boolean'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation error',
                    'errors' => $validator->errors()
                ], 422);
            }

            $query = RoleMaster::withCount(['users as total_users', 'users as default_users' => function ($query) {
                $query->where('default_rid', 1);
            }]);

            if ($request->has('active_only')) {
                $query->where('Is_Active', $request->boolean('active_only'));
            }

            $roles = $query->get();

            return response()->json([
                'success' => true,
                'message' => 'Roles with user count fetched successfully',
                'data' => $roles
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch roles with user count',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    /**
     * Bulk create roles.
     */
    public function bulkStore(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'roles' => 'required|array|min:1|max:50',
                'roles.*.Role_Prefix' => 'nullable|string|max:5',
                'roles.*.Role_Name' => 'required|string|max:25',
                'roles.*.TwoFacAuth' => 'nullable|string|in:Y,N',
                'roles.*.Is_Active' => 'nullable|boolean'
            ], RoleMaster::validationMessages());

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation error',
                    'errors' => $validator->errors()
                ], 422);
            }

            $createdRoles = [];
            $errors = [];

            foreach ($request->roles as $index => $roleData) {
                try {
                    // Additional validation for each role
                    $roleValidator = Validator::make($roleData, [
                        'Role_Name' => 'required|string|max:50|unique:role_master,Role_Name',
                        'Role_Prefix' => 'nullable|string|max:5',
                        'TwoFacAuth' => 'nullable|string|in:Y,N',
                        'Is_Active' => 'nullable|boolean'
                    ], RoleMaster::validationMessages());

                    if ($roleValidator->fails()) {
                        $errors[] = [
                            'index' => $index,
                            'data' => $roleData,
                            'errors' => $roleValidator->errors()->toArray()
                        ];
                        continue;
                    }

                    $role = RoleMaster::create([
                        'Role_Prefix' => $roleData['Role_Prefix'] ?? null,
                        'Role_Name' => $roleData['Role_Name'],
                        'TwoFacAuth' => $roleData['TwoFacAuth'] ?? null,
                        'Is_Active' => $roleData['Is_Active'] ?? true
                    ]);

                    $createdRoles[] = $role;
                } catch (\Exception $e) {
                    $errors[] = [
                        'index' => $index,
                        'data' => $roleData,
                        'message' => 'Something went wrong. Please try again later.'
                    ];
                }
            }

            $response = [
                'success' => true,
                'message' => count($createdRoles) . ' role(s) created successfully',
                'data' => $createdRoles,
                'total_created' => count($createdRoles),
                'total_failed' => count($errors)
            ];

            if (count($errors) > 0) {
                $response['errors'] = $errors;
            }

            return response()->json($response, count($createdRoles) > 0 ? 201 : 400);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create bulk roles',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }
}
