<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\RoleMaster;

class RoleMasterController extends Controller
{
    // Get all roles
    public function index()
    {
        return RoleMaster::all();
    }

    // Create a new role
    public function store(Request $request)
    {
        // Validate the request data
        $request->validate([
            'Role_Name' => 'required|string|max:25'
        ]);

        // Create a new role
        $role = new RoleMaster();
        $role->Role_Name = $request->Role_Name;
        $role->save();

        // Return response with the created role details
        return response()->json([
            'message' => 'Role added successfully',
            'role' => $role
        ], 201);
    }

    // Get a role by ID
    public function show($id)
    {
        return RoleMaster::find($id);
    }

    // Update a role
    public function update(Request $request, $id)
    {
        $role = RoleMaster::find($id);

        // Check if the role exists
        if ($role) {
            // Validate the request data
            $request->validate([
                'Role_Name' => 'required|string|max:25'
            ]);

            // Update role details
            $role->Role_Name = $request->Role_Name;
            $role->save();

            // Return response with the updated role details
            return response()->json([
                'message' => 'Role updated successfully',
                'role' => $role
            ], 200);
        }

        // Return not found response if role doesn't exist
        return response()->json([
            'message' => 'Role not found'
        ], 404);
    }

    // Delete a role
    public function destroy($id)
    {
        $role = RoleMaster::find($id);
        if ($role) {
            $role->delete();
            return response()->json(['message' => 'Role deleted successfully']);
        }

        return response()->json(['message' => 'Role not found'], 404);
    }
}
