<?php

namespace App\Http\Controllers;

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

class AdminUserController extends Controller
{
    public function index()
    {
        $users = AdminUser::all();
        return response()->json($users);
    }

    public function show($id)
    {
        $user = AdminUser::findOrFail($id);
        return response()->json($user);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'username' => 'required|string|max:50|unique:admin_users',
            'password' => 'required|string',
            'role' => 'nullable|integer',
        ]);
        $data['password'] = bcrypt($data['password']);
        $user = AdminUser::create($data);
        return response()->json($user, 201);
    }

    public function update(Request $request, $id)
    {
        $user = AdminUser::findOrFail($id);
        $data = $request->validate([
            'username' => 'sometimes|string|max:50|unique:admin_users,username,' . $id,
            'password' => 'sometimes|string',
            'role' => 'sometimes|integer',
        ]);
        if (isset($data['password'])) {
            $data['password'] = bcrypt($data['password']);
        }
        $user->update($data);
        return response()->json($user);
    }

    public function destroy($id)
    {
        $user = AdminUser::findOrFail($id);
        $user->delete();
        return response()->json(null, 204);
    }
}
