<?php
namespace App\Controllers\Qc;

use CodeIgniter\API\ResponseTrait;
use App\Controllers\BaseController;
use App\Models\Qc\ControlTestsModel;

class ControlTestsController extends BaseController
{
    use ResponseTrait;

    protected $model;
    protected $rules = [
        'controlId' => 'required|numeric',
        'testId' => 'required|numeric',
        'mean' => 'required|decimal',
        'sd' => 'required|decimal',
    ];

    public function __construct()
    {
        $this->model = new ControlTestsModel();
    }

    public function index()
    {
        $keyword = $this->request->getGet('keyword');
        return $this->respond([
            'status' => 'success',
            'data' => $this->model->search($keyword)
        ]);
    }

    public function create()
    {
        $input = $this->request->getJSON(true);
        if (!$this->validate($this->rules)) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        try {
            $id = $this->model->insert($input);
            return $this->respondCreated(['status' => 'success', 'data' => $id]);
        } catch (\Exception $e) {
            return $this->failServerError($e->getMessage());
        }
    }

    public function update($id = null)
    {
        $input = $this->request->getJSON(true);
        if (!$this->validate($this->rules)) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        try {
            $this->model->update($id, $input);
            return $this->respond(['status' => 'success']);
        } catch (\Exception $e) {
            return $this->failServerError($e->getMessage());
        }
    }

    public function delete($id = null)
    {
        try {
            $this->model->delete($id);
            return $this->respond(['status' => 'success']);
        } catch (\Exception $e) {
            return $this->failServerError($e->getMessage());
        }
    }
}
