<?php

namespace App\Controllers\Api;

use App\Models\UserModel;

class UserController extends BaseApiController
{
protected $user;

public function __construct()
{
$this->user = new UserModel();
}

// 🔒 ADMIN ONLY
public function index()
{
return $this->respondSuccess(
$this->user->findAll(),
'Data user'
);
}

public function store()
{
$data = $this->request->getJSON(true);

$insert = [

'username' => $data['username'],
'password' => password_hash($data['password'], PASSWORD_BCRYPT),
'nama' => $data['nama'],
'role' => $data['role'] ?? 'petugas',
];

$this->user->insert($insert);

return $this->respondSuccess(null, 'User berhasil ditambahkan');
}

public function update($id)
{
$data = $this->request->getJSON(true);

$update = [
'nama' => $data['nama'],
'role' => $data['role'],
'status' => $data['status'],
];

// 🔐 jika admin isi password baru
if (!empty($data['password'])) {
$update['password'] = password_hash(
$data['password'],
PASSWORD_BCRYPT
);
}

$this->user->update($id, $update);

return $this->respondSuccess(null, 'User diperbarui');
}

//public function delete($id)
//{
//$this->user->delete($id);
//return $this->respondSuccess(null, 'User dihapus');
//}
}