tinyqc/app/Controllers/Api/DeptApiController.php

106 lines
2.6 KiB
PHP
Raw Normal View History

<?php
namespace App\Controllers\Api;
use App\Controllers\BaseController;
use App\Models\DictDeptModel;
class DeptApiController extends BaseController
{
protected $dictDeptModel;
public function __construct()
{
$this->dictDeptModel = new DictDeptModel();
}
public function index()
{
$depts = $this->dictDeptModel->findAll();
return $this->response->setJSON([
'status' => 'success',
'message' => 'Departments fetched successfully',
'data' => $depts
]);
}
public function show($id)
{
$dept = $this->dictDeptModel->find($id);
if (!$dept) {
return $this->response->setJSON([
'status' => 'error',
'message' => 'Department not found'
])->setStatusCode(404);
}
return $this->response->setJSON([
'status' => 'success',
'data' => $dept
]);
}
public function store()
{
$post = $this->request->getJSON(true);
$data = [
'name' => $post['name'] ?? '',
];
$id = $this->dictDeptModel->insert($data);
if ($id) {
return $this->response->setJSON([
'status' => 'success',
'message' => 'Department saved successfully',
'data' => ['dept_id' => $id]
]);
}
return $this->response->setJSON([
'status' => 'error',
'message' => 'Failed to save department'
])->setStatusCode(500);
}
public function update($id)
{
$post = $this->request->getJSON(true);
$data = [
'name' => $post['name'] ?? '',
];
$success = $this->dictDeptModel->update($id, $data);
if ($success) {
return $this->response->setJSON([
'status' => 'success',
'message' => 'Department updated successfully'
]);
}
return $this->response->setJSON([
'status' => 'error',
'message' => 'Failed to update department'
])->setStatusCode(500);
}
public function delete($id)
{
$success = $this->dictDeptModel->delete($id);
if ($success) {
return $this->response->setJSON([
'status' => 'success',
'message' => 'Department deleted successfully'
]);
}
return $this->response->setJSON([
'status' => 'error',
'message' => 'Failed to delete department'
])->setStatusCode(500);
}
}