<?php
namespace View\Main;
use Controller\Main;
use Model\DomainModel\Member;
use Model\DomainModel\OwnedItem;
use Model\DomainModel\Item;
use Resource\Collection\LinkedList;
use Resource\Core\Registry;
use Resource\Core\Model;
use Resource\Core\View;
use Resource\GUI\Document\Comment;
use Resource\GUI\Container\Form;
use Resource\GUI\Component\Button;
use Resource\GUI\Container\DropdownList;
use Resource\GUI\Component\PasswordField;
use Resource\GUI\Component\Option;
class FarmView extends View {
private $seedToHarvestMap = [
50 => ['id' => 51, 'name' => 'Carrot'],// 32 is the ID of the seed item players need to have. 17 is the ID of the final harvested crop item.
// Add more
52 => ['id' => 53, 'name' => 'Turnip'],
54 => ['id' => 55, 'name' => 'Pepper'],
];
public function index() {
$mysidia = Registry::get("mysidia");
$document = $this->document;
$requiredWaterCan = new OwnedItem(49, $mysidia->user->getID()); // Changed to 7
$farmStage = $mysidia->user->getFarmStage();
$document->setTitle("My Farm");
$document->add(new Comment("You can buy seeds at the <a href='
https://monstari.mysidiahost.com/shop/browse/1'>General Store</a> and plant them in your farm. You can only water them once a day, but after a few days, you should be able to harvest!"));
$document->add(new Comment("<div class='farmplots'>"));
if ($requiredWaterCan->inInventory() && $farmStage == 0) {
$plots = 5;
$seedsAvailable = $this->getSeeds($mysidia->user->getID());
$userPlants = $this->getUserPlants($mysidia->user->getID());
for ($i = 0; $i < $plots; $i++) {
$plot = isset($userPlants[$i]) ? $userPlants[$i] : null;
$this->renderPlot($document, $plot, $seedsAvailable, $i + 1);
}
$this->handlePost($mysidia, $document);
} elseif ($requiredWaterCan->inInventory() && $farmStage == 1) {
$plots = 4;
$seedsAvailable = $this->getSeeds($mysidia->user->getID());
$userPlants = $this->getUserPlants($mysidia->user->getID());
for ($i = 0; $i < $plots; $i++) {
$plot = isset($userPlants[$i]) ? $userPlants[$i] : null;
$this->renderPlot($document, $plot, $seedsAvailable, $i + 1);
}
$this->handlePost($mysidia, $document);
} elseif ($requiredWaterCan->inInventory() && $farmStage == 2) {
$plots = 6;
$seedsAvailable = $this->getSeeds($mysidia->user->getID());
$userPlants = $this->getUserPlants($mysidia->user->getID());
for ($i = 0; $i < $plots; $i++) {
$plot = isset($userPlants[$i]) ? $userPlants[$i] : null;
$this->renderPlot($document, $plot, $seedsAvailable, $i + 1);
}
$this->handlePost($mysidia, $document);
} elseif ($requiredWaterCan->inInventory() && $farmStage == 3) {
$plots = 8;
$seedsAvailable = $this->getSeeds($mysidia->user->getID());
$userPlants = $this->getUserPlants($mysidia->user->getID());
for ($i = 0; $i < $plots; $i++) {
$plot = isset($userPlants[$i]) ? $userPlants[$i] : null;
$this->renderPlot($document, $plot, $seedsAvailable, $i + 1);
}
$this->handlePost($mysidia, $document);
} elseif ($requiredWaterCan->inInventory() && $farmStage == 4) {
$plots = 10;
$seedsAvailable = $this->getSeeds($mysidia->user->getID());
$userPlants = $this->getUserPlants($mysidia->user->getID());
for ($i = 0; $i < $plots; $i++) {
$plot = isset($userPlants[$i]) ? $userPlants[$i] : null;
$this->renderPlot($document, $plot, $seedsAvailable, $i + 1);
}
$this->handlePost($mysidia, $document);
} else {
$document->add(new Comment("You need a Watering Can to work on your farm. Please visit the store to purchase one."));
}
$document->add(new Comment("</div>"));
}
private function getSeeds($uid) {
$mysidia = Registry::get("mysidia");
// Prepare and execute the query to fetch seed names
$query = "SELECT adopts_inventory.item, adopts_inventory.quantity, adopts_items.itemname
FROM adopts_inventory
JOIN adopts_items ON adopts_inventory.item = adopts_items.id
WHERE adopts_inventory.owner =

wner AND adopts_inventory.item IN (50, 52, 55, 54, 57, 58, 59, 60, 61, 62) AND adopts_inventory.quantity > 0";
$stmt = $mysidia->db->prepare($query);
$stmt->execute(["owner" => $uid]);
return $stmt->fetchAll();
}
private function getUserPlants($uid) {
$mysidia = Registry::get("mysidia");
return $mysidia->db->select("users_plants", [], "uid='{$uid}'")->fetchAll();
}
private function renderPlot($document, $plot, $seedsAvailable, $plotNumber) {
if ($plot) {
$plantStage = $plot['cropstage'];
$plantWatered = $plot['plantwatered'];
$wateredDay = $plot['wateredday'];
$currentDay = date("d");
$cropName = isset($this->seedToHarvestMap[$plot['crop']]) ? $this->seedToHarvestMap[$plot['crop']]['name'] : 'Unknown Crop';
$imagePath = "images/items/farming/{$cropName}/Plant_{$cropName}_GrowthStage{$plantStage}.png";
$document->add(new Comment("<div class='singleplot'>"));
$document->add(new Comment("<img src='{$imagePath}' alt='Plant Stage {$plantStage}'>"));
if ($plantStage < 6) {
if (($plantWatered == 1) && $wateredDay == $currentDay) {
$action = "Watered";
} else {
$action = "Water";
}
$this->renderActionForm($document, $action, $plot['pid']);
} else {
$this->renderActionForm($document, "Harvest", $plot['pid']);
}
} else {
$document->add(new Comment("<div class='singleplot'>"));
$document->add(new Comment("<img src='images/items/farming/dirtmound.png' alt='Empty Plot'>"));
$this->renderPlantForm($document, $seedsAvailable, $plotNumber);
}
$document->add(new Comment("</div>"));
}
private function renderActionForm($document, $action, $plotID) {
$form = new Form("plotActionForm", "farm", "post"); // Updated action URL to "farm"
$form->add(new PasswordField("hidden", "action", strtolower($action)));
$form->add(new PasswordField("hidden", "plotID", $plotID)); // Ensure plotID is captured
$form->add(new Button($action, "submit", "submit"));
$document->add($form);
}
private function renderPlantForm($document, $seedsAvailable, $plotNumber) {
$form = new Form("plantForm", "farm", "post"); // Ensure form action and method are set correctly
$dropdown = new DropdownList("seedID");
foreach ($seedsAvailable as $seed) {
$dropdown->add(new Option("{$seed['itemname']} ({$seed['quantity']})", $seed['item']));
}
$form->add($dropdown);
$form->add(new PasswordField("hidden", "plotNumber", $plotNumber));
$form->add(new PasswordField("hidden", "action", "plant")); // Add action hidden field
$form->add(new Button("Plant", "submit", "submit"));
$document->add($form);
}
private function handlePost($mysidia, $document) {
if ($_POST) {
if ($mysidia->input->post("action")) {
$action = $mysidia->input->post("action");
$plotID = $mysidia->input->post("plotID");
$plotNumber = $mysidia->input->post("plotNumber");
if ($action == "plant") {
$seedID = $mysidia->input->post("seedID");
$this->plantCrop($mysidia->user->getID(), $plotNumber, $seedID, $document);
$this->refresh(1);
return;
} elseif ($action == "water") {
$this->waterCrop($plotID, $document);
$this->refresh(1);
return;
} elseif ($action == "harvest") {
$this->harvestCrop($plotID, $document);
$this->refresh(1);
return;
}
}
} else {
}
}
private function plantCrop($uid, $plotNumber, $seedID, $document) {
$mysidia = Registry::get("mysidia");
$currentQuantity = $mysidia->db->select("inventory", ["quantity"], "owner='{$uid}' AND item='{$seedID}'")->fetchColumn();
if ($currentQuantity < 1) {
$errorMessage = "You do not have enough seeds to plant.";
$document->add(new Comment("<div class='errormessage'>{$errorMessage}</div>"));
return;
}
// Add a new row in users_plants
$mysidia->db->insert("users_plants", [
"uid" => $uid,
"crop" => $seedID,
"wateredday" => date("d"), // Ensure correct date format
"cropstage" => 1,
"plantwatered" => 0
]);
// Retrieve the last inserted ID to get the unique plot ID (pid)
$plotID = $mysidia->db->lastInsertId();
// Update inventory to decrease seed count
$mysidia->db->update("inventory", ["quantity" => $currentQuantity - 1], "owner='{$uid}' AND item='{$seedID}'");
// Debug Output to check inventory after updating
$updatedQuantity = $mysidia->db->select("inventory", ["quantity"], "owner='{$uid}' AND item='{$seedID}'")->fetchColumn();
$seedremove = new OwnedItem("{$seedID}", $mysidia->user->getID());
$successMessage = "You have successfully planted the seeds!";
$document->add(new Comment("<div class='successmessage'>{$successMessage}</div>"));
$seedremove->remove(1, $uid);
$this->refresh(3);
return;
}
private function waterCrop($plotID, $document) {
$mysidia = Registry::get("mysidia");
// Get current crop stage and watered day
$cropData = $mysidia->db->select("users_plants", ["cropstage", "wateredday"], "pid='{$plotID}'")->fetchObject();
$currentDay = date("d");
if ($cropData->wateredday == $currentDay) {
$errorMessage = "You have already watered this plant today.";
$document->add(new Comment("<div class='errormessage'>{$errorMessage}</div>"));
$this->refresh(3);
return;
}
$newStage = min($cropData->cropstage + 1, 6); // Ensure stage doesn't exceed 6
// Update the crop stage and set plantwatered to 1 and update wateredday
$mysidia->db->update("users_plants", ["cropstage" => $newStage, "plantwatered" => 1, "wateredday" => $currentDay], "pid='{$plotID}'");
$successMessage = "You have successfully watered the plant!";
$document->add(new Comment("<div class='successmessage'>{$successMessage}</div>"));
$this->refresh(3);
return;
}
private function harvestCrop($plotID, $document) {
$mysidia = Registry::get("mysidia");
// Get crop type to determine the harvested item
$cropData = $mysidia->db->select("users_plants", ["crop"], "pid='{$plotID}'")->fetchObject();
// Use the mapping array to get the corresponding harvestable item ID
$harvestItemID = $this->seedToHarvestMap[$cropData->crop]['id'];
// Add harvested item to user's inventory
$mysidia->db->insert("inventory", [
"owner" => $mysidia->user->getID(),
"item" => $harvestItemID,
"quantity" => 5
]);
// Remove the plant from users_plants
$mysidia->db->delete("users_plants", "pid='{$plotID}'");
$successMessage = "You have successfully harvested the crop!";
$document->add(new Comment("<div class='successmessage'>{$successMessage}</div>"));
}
}
?>