dictControlModel = new DictControlModel(); $this->controlTestModel = new ControlTestModel(); } public function index() { $controls = $this->dictControlModel->getWithDept(); return $this->response->setJSON([ 'status' => 'success', 'message' => 'Controls fetched successfully', 'data' => $controls ]); } public function show($id) { $control = $this->dictControlModel->find($id); if (!$control) { return $this->response->setJSON([ 'status' => 'error', 'message' => 'Control not found' ])->setStatusCode(404); } return $this->response->setJSON([ 'status' => 'success', 'data' => $control ]); } public function getTests($id) { $tests = $this->controlTestModel->where('control_ref_id', $id)->findAll(); $testIds = array_column($tests, 'test_ref_id'); return $this->response->setJSON([ 'status' => 'success', 'data' => $testIds ]); } public function store() { $post = $this->request->getJSON(true); $controlData = [ 'dept_ref_id' => $post['dept_ref_id'] ?? null, 'name' => $post['name'] ?? '', 'lot' => $post['lot'] ?? '', 'producer' => $post['producer'] ?? '', 'expdate' => $post['expdate'] ?? null, ]; $controlId = $this->dictControlModel->insert($controlData, true); if (!empty($post['test_ids'])) { foreach ($post['test_ids'] as $testId) { $this->controlTestModel->insert([ 'control_ref_id' => $controlId, 'test_ref_id' => $testId, 'mean' => 0, 'sd' => 0, ]); } } if ($controlId) { return $this->response->setJSON([ 'status' => 'success', 'message' => 'Control saved successfully', 'data' => ['control_id' => $controlId] ]); } return $this->response->setJSON([ 'status' => 'error', 'message' => 'Failed to save control' ])->setStatusCode(500); } public function update($id) { $post = $this->request->getJSON(true); $controlData = [ 'dept_ref_id' => $post['dept_ref_id'] ?? null, 'name' => $post['name'] ?? '', 'lot' => $post['lot'] ?? '', 'producer' => $post['producer'] ?? '', 'expdate' => $post['expdate'] ?? null, ]; $success = $this->dictControlModel->update($id, $controlData); if (!empty($post['test_ids'])) { $this->controlTestModel->where('control_ref_id', $id)->delete(); foreach ($post['test_ids'] as $testId) { $this->controlTestModel->insert([ 'control_ref_id' => $id, 'test_ref_id' => $testId, 'mean' => 0, 'sd' => 0, ]); } } if ($success) { return $this->response->setJSON([ 'status' => 'success', 'message' => 'Control updated successfully' ]); } return $this->response->setJSON([ 'status' => 'error', 'message' => 'Failed to update control' ])->setStatusCode(500); } public function delete($id) { $this->controlTestModel->where('control_ref_id', $id)->delete(); $success = $this->dictControlModel->delete($id); if ($success) { return $this->response->setJSON([ 'status' => 'success', 'message' => 'Control deleted successfully' ]); } return $this->response->setJSON([ 'status' => 'error', 'message' => 'Failed to delete control' ])->setStatusCode(500); } }