clqms-be/app/Controllers/CounterController.php

70 lines
2.6 KiB
PHP

<?php
namespace App\Controllers;
use App\Traits\ResponseTrait;
use App\Controllers\BaseController;
use App\Models\CounterModel;
class CounterController extends BaseController {
use ResponseTrait;
protected $model;
public function __construct() {
$this->model = new CounterModel();
}
public function index() {
$rows = $this->model->findAll();
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($CounterID = null) {
$row = $this->model->find($CounterID);
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);
try {
$id = $this->model->insert($input,true);
return $this->respondCreated([ 'status' => 'success', 'message' => 'Data created successfully', 'data' => $id ], 201);
} catch (\Throwable $e) {
return $this->failServerError('Something went wrong: ' . $e->getMessage());
}
}
public function update($CounterID = null) {
$input = $this->request->getJSON(true);
if (!$CounterID || !ctype_digit((string) $CounterID)) {
return $this->respond(['status' => 'error', 'message' => 'CounterID is required and must be a valid integer'], 400);
}
$input['CounterID'] = (int) $CounterID;
try {
$this->model->update($input['CounterID'], $input);
return $this->respondCreated([ 'status' => 'success', 'message' => 'Data updated successfully', 'data' => $input['CounterID'] ], 201);
} catch (\Throwable $e) {
return $this->failServerError('Something went wrong: ' . $e->getMessage());
}
}
public function delete() {
$input = $this->request->getJSON(true);
try {
$this->model->delete($input['CounterID'], $input);
return $this->respondCreated([ 'status' => 'success', 'message' => 'Data deleted successfully', 'data' => $input['CounterID'] ], 201);
} catch (\Throwable $e) {
return $this->failServerError('Something went wrong: ' . $e->getMessage());
}
}
}