<?php

namespace App\Http\Controllers\SM;

use App\Http\Controllers\Controller;
use App\Services\SM\PermissionService;
use App\Traits\DataTable;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PermissionController extends Controller
{
    /**
     * Display a listing of the resource.
     */

    use DataTable;
    public function __construct(private PermissionService $permissionService)
    {
    }
    public function index()
    {
        try {
            $data = $this->permissionService->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->permissionService->create($request->all());
            DB::commit();
            return response()->json(['permission' => $permission, 'message' => 'Permission created']);
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['message' => $e->getMessage()], 500);
        }
    }

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

    /**
     * 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();
            $this->permissionService->update($id,$request->all());
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false,'message' => $e->getMessage()]);
        }
    }

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