<?php
namespace App\Controllers\ValueSet;

use CodeIgniter\API\ResponseTrait;
use App\Controllers\BaseController;
use App\Models\ValueSet\ValueSetDefModel;

class ValueSetDefController extends BaseController {
    use ResponseTrait;

    protected $db;
    protected $rules;
    protected $model;

    public function __construct() {
        $this->db = \Config\Database::connect();
        $this->model = new ValueSetDefModel;
        $this->rules = [
            'VSName' => 'required',
            'VSDesc' => 'required'
        ];
    }

    public function index() {
        $param = $this->request->getVar('param');
        $rows = $this->model->getValueSetDefs($param);
        if (empty($rows)) { return $this->respond([ 'status'  => 'success', 'message' => "no Data.", 'data' => [] ], 200); }
        return $this->respond([ 'status' => 'success', 'message'=> "Data fetched successfully", 'data' => $rows ], 200); 
    }

    public function show($VSetID = null) {
        $row = $this->model->find($VSetID);
        if (empty($row)) { return $this->respond([ 'status'  => 'success', 'message' => "no Data.", 'data' => null ], 200); }
        return $this->respond([ 'status' => 'success', 'message'=> "Data fetched successfully", 'data' => $row ], 200); 
    }

    public function create() {
        $input = $this->request->getJSON(true);
        if (!$this->validateData($input, $this->rules)) { return $this->failValidationErrors($this->validator->getErrors()); }
        try {
            $VSetID = $this->model->insert($input);
            return $this->respondCreated([ 'status'  => 'success', 'message' => "data $VSetID created successfully" ]);
        } catch (\Exception $e) {
            return $this->failServerError('Something went wrong: ' . $e->getMessage());
        }
    }

    public function update() {
        $input = $this->request->getJSON(true);
        $VSetID = $input["VSetID"];
        if (!$VSetID) { return $this->failValidationErrors('VSetID is required.'); }
        if (!$this->validateData($input, $this->rules)) { return $this->failValidationErrors( $this->validator->getErrors() ); }
        try {
					$this->model->update($VSetID,$input);
					return $this->respondCreated([ 'status'  => 'success', 'message' => "data $VSetID updated successfully" ]);
        } catch (\Exception $e) {
            return $this->failServerError('Something went wrong: ' . $e->getMessage());
        }
    }

    public function delete() {
        $input = $this->request->getJSON(true);
        $VSetID = $input['VSetID'];
        if (!$VSetID) { return $this->failValidationErrors('VSetID is required.'); }
        try {
            $this->model->delete($VSetID);
            return $this->respondDeleted(['status' => 'success', 'message' => "Data $VSetID deleted successfully."]);
        } catch (\Throwable $e) {
            return $this->failServerError('Something went wrong: ' . $e->getMessage());
        }
    }

}
