<?php

namespace App\Http\Controllers;

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

class UnitKerjaController extends Controller
{
    public function index()
    {
        $data = UnitKerja::all();
        return response()->json([
            'success' => true,
            'data' => $data
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'nama_unit' => 'required|unique:unit_kerja,nama_unit',
        ]);

        $unit = UnitKerja::create($request->all());

        return response()->json([
            'success' => true,
            'message' => 'Unit Kerja berhasil ditambah',
            'data' => $unit
        ]);
    }

    public function show($id)
    {
        $unit = UnitKerja::find($id);
        if (!$unit) return response()->json(['message' => 'Data tidak ditemukan'], 404);

        return response()->json(['success' => true, 'data' => $unit]);
    }

    public function update(Request $request, $id)
    {
        $unit = UnitKerja::find($id);
        if (!$unit) return response()->json(['message' => 'Data tidak ditemukan'], 404);

        $unit->update($request->all());

        return response()->json([
            'success' => true,
            'message' => 'Unit Kerja berhasil diupdate'
        ]);
    }

    public function destroy($id)
    {
        $unit = UnitKerja::find($id);
        if (!$unit) return response()->json(['message' => 'Data tidak ditemukan'], 404);

        $unit->delete();
        return response()->json(['success' => true, 'message' => 'Unit Kerja dihapus']);
    }
}