<?php

namespace App\Http\Controllers\SM;

use App\Http\Controllers\Controller;
use App\Services\SM\RoleService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RoleController extends Controller
{

    public function __construct(private RoleService $roleService)
    {
        
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        try {
            $data = $this->roleService->dataTable();
            return response()->json($data);
        } catch (Exception $e) {
            return response()->json(['data' => [], 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            DB::beginTransaction();
            $permission = $this->roleService->create($request->all());
            DB::commit();
            return response()->json(['role' => $permission, 'message' => 'Role created']);
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['message' => $e->getMessage()], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $role = $this->roleService->detail($id);
        return response()->json(['role' => $role]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        try {
            DB::beginTransaction();
            $permission = $this->roleService->update($id,$request->all());
            DB::commit();
            return response()->json(['role' => $permission, 'message' => 'Role updated']);
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['message' => $e->getMessage()], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
