clqms-be/app/Controllers/LocationController.php

84 lines
3.2 KiB
PHP

<?php
namespace App\Controllers;
use App\Traits\ResponseTrait;
use App\Controllers\BaseController;
use App\Models\Location\LocationModel;
class LocationController extends BaseController {
use ResponseTrait;
protected $model;
protected $rules;
public function __construct() {
$this->model = new LocationModel();
$this->rules = [
'LocCode' => 'required|max_length[6]',
'LocFull' => 'required',
];
}
public function index() {
$LocName = $this->request->getVar('LocName');
$LocCode = $this->request->getVar('LocCode');
$rows = $this->model->getLocations($LocCode,$LocName);
if (empty($rows)) {
return $this->respond([ 'status' => 'success', 'message' => "no Data.", 'data' => [] ], 200);
}
return $this->respond([ 'status' => 'success', 'message'=> "fetch success", 'data' => $rows ], 200);
}
public function show($LocationID = null) {
$row = $this->model->getLocation($LocationID);
if (empty($row)) {
return $this->respond([ 'status' => 'success', 'message' => "no Data.", 'data' => null ], 200);
}
return $this->respond([ 'status' => 'success', 'message'=> "fetch success", 'data' => $row ], 200);
}
public function create() {
$input = $this->request->getJSON(true);
if (!$this->validateData($input, $this->rules)) { return $this->failValidationErrors($this->validator->getErrors()); }
try {
$result = $this->model->saveLocation($input);
return $this->respondCreated([ 'status' => 'success', 'message' => 'data created successfully', 'data' => $result ], 201);
} catch (\Throwable $e) {
return $this->failServerError('Something went wrong: ' . $e->getMessage());
}
}
public function update($LocationID = null) {
$input = $this->request->getJSON(true);
if (!$LocationID || !ctype_digit((string) $LocationID)) {
return $this->respond([
'status' => 'failed',
'message' => 'LocationID is required and must be a valid integer',
'data' => []
], 400);
}
$input['LocationID'] = (int) $LocationID;
try {
if (!$this->validateData($input, $this->rules)) { return $this->failValidationErrors( $this->validator->getErrors()); }
$result = $this->model->saveLocation($input, true);
return $this->respondCreated([ 'status' => 'success', 'message' => 'data updated successfully', 'data' => $result ], 201);
} catch (\Throwable $e) {
return $this->failServerError('Something went wrong: ' . $e->getMessage());
}
}
public function delete() {
$input = $this->request->getJSON(true);
try {
$LocationID = $input["LocationID"];
$this->model->deleteLocation($LocationID);
return $this->respondDeleted([ 'status' => 'success', 'message' => "Location with {$LocationID} deleted successfully." ]);
} catch (\Throwable $e) {
return $this->failServerError('Something went wrong: ' . $e->getMessage());
}
}
}