<?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();

            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' => $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' => $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' => $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' => $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' => $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'
        ]);
    }
}
