<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class JabatanController extends Controller
{
    function simpanDataJabatan(Request $request)
    {
        $nama_jabatan = $request->nama_jabatan;
        DB::beginTransaction();
        try {
            if (DB::table('ref_jabatan')->where('nama_jabatan', $nama_jabatan)->count() > 0) {
                return response()->json([
                    "success" => false,
                    "error" => "Duplikat jabatan"
                ]);
            }
            DB::table('ref_jabatan')->insert([
                'nama_jabatan' => $nama_jabatan,
                'deskripsi' => $request->deskripsi
            ]);
            DB::commit();
            return response()->json([
                "success" => true,
                "message" => "Data berhasil disimpan"
            ]);
        } catch (Exception $error) {
            DB::rollBack();
            return response()->json([
                "success" => false,
                "error" => $error->getMessage()
            ]);
        }
    }

    function updateDataJabatan(Request $request)
    {
        $id_jabatan = $request->id_jabatan;
        $nama_jabatan = $request->nama_jabatan;
        DB::beginTransaction();
        try {
            DB::table('ref_jabatan')
                ->where('id_jabatan', $id_jabatan)
                ->update([
                    'nama_jabatan' => $nama_jabatan,
                    'deskripsi' => $request->deskripsi
                ]);
            DB::commit();
            return response()->json([
                "success" => true,
                "message" => "Data berhasil disimpan"
            ]);
        } catch (Exception $error) {
            DB::rollBack();
            return response()->json([
                "success" => false,
                "error" => $error->getMessage()
            ]);
        }
    }

    function getDaftarJabatan()
    {
        try {
            $jabatan = DB::table('ref_jabatan')->get();
            return response()->json([
                "success" => true,
                "data" => $jabatan
            ]);
        } catch (Exception $error) {
            return response()->json([
                "success" => false,
                "error" => $error->getMessage()
            ]);
        }
    }

    function getDetailJabatan(Request $request)
    {
        try {
            $jabatan = DB::table('ref_jabatan')->where('id_jabatan', $request->id)->first();
            return response()->json([
                "success" => true,
                "data" => $jabatan
            ]);
        } catch (Exception $error) {
            return response()->json([
                "success" => false,
                "error" => $error->getMessage()
            ]);
        }
    }
}
