File: /var/www/farm.kosmicfarms/app/controllers/WaterController.php
<?php
use Phalcon\Mvc\Controller;
use Phalcon\Http\Response;
use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;
use Phalcon\Mvc\Model\Transaction\Manager as TxManager;
class WaterController extends ControllerBase
{
public function initialize()
{
// Sets 'common' as the template to be rendered BEFORE the main layout
$this->view->setVar('body_css', "g-sidenav-show bg-gray-100");
$this->view->setVar('page_title', "Water Management");
// Pass to view
$this->view->locations = Locations::find();
// In your controller
$tanks = $this->modelsManager->createBuilder()
->columns([
'wt.id', // ID from the primary table
't.name AS name' // Name from the foreign key table
])
->from(['t' => Tanks::class])
->join(Water::class, 't.id = wt.tank_id', 'wt')
->getQuery()
->execute();
$this->view->tanks = $tanks;
}
public function indexAction()
{
$sum = $this->modelsManager->createBuilder()
->columns('SUM(b.capacity) as total')
->from(['b' => Tanks::class])
->join(Water::class, 'wt.tank_id = b.id', 'wt')
->getQuery()
->getSingleResult();
$max_water_capacity = $sum->total ?? 0;;
$this->view->setVar('max_water_capacity', $max_water_capacity);
$total_water_volume = Water::sum([ "column" => "capacity"]) ?? 0;;
$this->view->setVar('total_water_volume', $total_water_volume);
$tanks = Water::count() ?? 0;;
$count = $this->modelsManager->createBuilder()
->columns('COUNT(wt.id) as total')
->from(['b' => Tanks::class])
->join(Water::class, 'wt.tank_id = b.id', 'wt')
->where('b.status = :status:', ['status' => 'active'])
->getQuery()
->getSingleResult();
$active_tanks = $count->total ?? 0;;
$this->view->setVar('active_tanks', $active_tanks);
$this->view->setVar('tanks', $tanks);
$watertanks = Water::find();
$this->view->setVar('watertanks', $watertanks);
// Count pumps where status is on
$active_pumps = Pumps::count([
"status = 'ON'",
]);
$this->view->setVar('active_pumps', $active_pumps);
$waterpumps = WaterPumps::find();
$this->view->setVar('waterpumps', $waterpumps);
$this->view->pick('water/index');
}
// Define a helper function to update a model
function updateTank(Tanks &$tank, Response &$response): bool
{
// Get the data from the request
$location = intval($this->request->getPost("location"));
if (empty($location)) {
// Return an error JSON response
$response->setJsonContent([
'status' => 'error',
'message' => 'Location cannot be empty.'
]);
return false;
}
$tank->location_id = $location;
$tank->type ="water";
$name = $this->request->getPost("name");
if (empty($name)) {
// Return an error JSON response
$response->setJsonContent([
'status' => 'error',
'message' => 'Name cannot be empty.'
]);
return false;
}
$tank->name = $name;
$max_capacity = $this->request->getPost("max_capacity");
if (empty($max_capacity)) {
// Return an error JSON response
$response->setJsonContent([
'status' => 'error',
'message' => 'Maximum capacity cannot be empty.'
]);
return false;
}
$tank->capacity = $max_capacity;
$tank_status = $this->request->getPost("tank_status");
if (empty($tank_status)) {
// Return an error JSON response
$response->setJsonContent([
'status' => 'error',
'message' => 'Maximum capacity cannot be empty.'
]);
return false;
}
$tank->status = $tank_status;
$installDate = $this->request->getPost("installDate");
if (empty($installDate)) {
// Return an error JSON response
$response->setJsonContent([
'status' => 'error',
'message' => 'Installation date cannot be empty.'
]);
return false;
}
$tank->installation_date = $installDate;
return true;
}
// Define a helper function to update a model
function updateWaterTank($tank_id, Water &$waterTank, Response &$response): bool
{
$waterTank->tank_id = $tank_id;
$waterTank->type = "rain";
$current_capacity = $this->request->getPost("current_capacity");
if (empty($current_capacity)) {
// Return an error JSON response
$response->setJsonContent([
'status' => 'error',
'message' => 'Current capacity cannot be empty.'
]);
return false;
}
$waterTank->capacity = $current_capacity;
return true;
}
public function addtankAction(){
// Disable the view component for this action
$this->view->disable();
$response = new Response();
// Check if the request is POST and AJAX
if ($this->request->isPost() && $this->request->isAjax()) {
try {
// 1. Create a transaction manager
$manager = new TxManager();
// 2. Request a transaction instance from the manager
$transaction = $manager->get();
/*
* Create Tank
*/
$tank = new Tanks();
$tank->setTransaction($transaction);
if($this->updateTank($tank, $response)){
if ($tank->save() === false) {
// Rollback if the first save fails
$transaction->rollback('Cannot save water tank');
return $response;
}
} else {
return $response;
}
/*
* Create water tank
*/
$waterTank = new Water();
$waterTank->setTransaction($transaction);
if($this->updateWaterTank($tank->id, $waterTank, $response)){
if ($waterTank->save() === false) {
// Rollback if the second save fails
$transaction->rollback('Cannot water tank');
return $response;
}
} else {
return $response;
}
// 5. If all operations are successful, commit the transaction
$transaction->commit();
// Return a success JSON response
$response->setJsonContent([
'status' => 'success',
'message' => 'Data received successfully!'
]);
} catch (TxFailed $e) {
return $this->response->setJsonContent([
'status' => 'ERROR',
'message' => $e->getMessage(),
'details' => $messages ?? 'Unknown error'
]);
}
} else {
// Handle non-AJAX or non-POST requests
$response->setJsonContent([
'status' => 'error',
'message' => 'Invalid request.'
]);
$response->setStatusCode(405, 'Method Not Allowed');
}
// Send the response back to the client
return $response;
}
public function gettankAction($id){
// Disable the view component for this action
$this->view->disable();
$response = new Response();
try {
$wt = Water::findFirst($id);
if (!$water) {
$response->setJsonContent([
'status' => 'error',
'message' => 'Invalid request.'
]);
$response->setStatusCode(405, 'Method Not Allowed');
}
$data = [
'status' => 'success',
'message' => 'Data retrieved successfully',
'data' => [
'id' => $wt->id,
'location' => $wt->tank->location_id,
'name' => $wt->tank->name,
'max_capacity' => $wt->tank->capacity,
'installDate' => $wt->tank->installation_date,
'tank_status' => $wt->tank->status,
'current_capacity' => $wt->capacity
]
];
return $this->response->setJsonContent($data);
} catch (TxFailed $e) {
$response->setJsonContent([
'status' => 'error',
'message' => 'Invalid request.'
]);
$response->setStatusCode(405, 'Method Not Allowed');
// Catch the transaction failed exception
} catch (\Exception $e) {
// Catch any other exceptions
$response->setJsonContent([
'status' => 'error',
'message' => 'Invalid request.'
]);
$response->setStatusCode(405, 'Method Not Allowed');
}
}
public function updateAction($id){
$this->view->disable();
$response = new Response();
try {
// Create a transaction manager
$manager = new TxManager();
// Request a transaction
$transaction = $manager->get();
$waterTank = Water::findFirst($id);
if (!$waterTank) {
$response->setJsonContent([
'status' => 'error',
'message' => 'Water Tank not found!'
]);
return $response;
}
$waterTank->setTransaction($transaction);
$tank = Tanks::findFirst($waterTank->tank_id);
if (!$tank) {
$response->setJsonContent([
'status' => 'error',
'message' => 'Water Tank not found!'
]);
return $response;
}
$tank->setTransaction($transaction);
// Define a helper function to update a model
if($this->updateTank($tank,$response)){
if ($tank->save() === false) {
// Rollback if the first save fails
$transaction->rollback('Cannot update water tank');
$response->setJsonContent([
'status' => 'error',
'message' => 'Unable to update!'
]);
return $response;
}
} else {
return $response;
}
if($this->updateWaterTank($tank->id, $waterTank,$response)){
if ($waterTank->save() === false) {
// Rollback if the first save fails
$transaction->rollback('Cannot save water tank');
$response->setJsonContent([
'status' => 'error',
'message' => 'Unable to update! Try again'
]);
return $response;
}
} else {
return $response;
}
// Everything went fine, commit the transaction
$transaction->commit();
$response->setJsonContent([
'status' => 'success',
'message' => 'Water tank updated successfully!'
]);
return $response;
} catch (TxFailed $e) {
$response->setJsonContent([
'status' => 'error',
'message' => 'Invalid request.'
]);
$response->setStatusCode(405, 'Method Not Allowed');
// Catch the transaction failed exception
} catch (\Exception $e) {
// Catch any other exceptions
$response->setJsonContent([
'status' => 'error',
'message' => 'Invalid request.'
]);
$response->setStatusCode(405, 'Method Not Allowed');
}
}
public function deleteAction($id){
$this->view->disable();
$response = new Response();
try {
// Create a transaction manager
$manager = new TxManager();
// Request a transaction
$transaction = $manager->get();
$waterTank = Water::findFirst($id);
if (!$waterTank) {
$response->setJsonContent([
'status' => 'error',
'message' => 'Water Tank not found!'
]);
return $response;
}
$waterTank->setTransaction($transaction);
$tank = Tanks::findFirst($waterTank->tank_id);
if (!$tank) {
$response->setJsonContent([
'status' => 'error',
'message' => 'Water Tank not found!'
]);
return $response;
}
$tank->setTransaction($transaction);
if($waterTank->delete() === false){
$transaction->rollback('Cannot delete water tank');
$msg = "Delete was unsuccessful";
foreach ($waterTank->getMessages() as $message) {
$msg += $message;
}
$response->setJsonContent([
'status' => 'error',
'message' => $nsg
]);
return $response;
} else {
if($tank->delete() === false){
$transaction->rollback('Cannot delete water tank');
$msg = "Delete was unsuccessful";
// Handle failure
foreach ($tank->getMessages() as $message) {
$msg += $message;
}
$response->setJsonContent([
'status' => 'error',
'message' => $msg
]);
return $response;
}
}
// Everything went fine, commit the transaction
$transaction->commit();
$response->setJsonContent([
'status' => 'success',
'message' => 'Water tank ____ deleted successfully.'
]);
return $response;
} catch (TxFailed $e) {
$response->setJsonContent([
'status' => 'error',
'message' => 'Invalid request.'
]);
$response->setStatusCode(405, 'Method Not Allowed');
// Catch the transaction failed exception
} catch (\Exception $e) {
// Catch any other exceptions
$response->setJsonContent([
'status' => 'error',
'message' => 'Invalid request.'
]);
$response->setStatusCode(405, 'Method Not Allowed');
}
}
}