diff --git a/.htaccess b/.htaccess index a589ab5..4444ee4 100644 --- a/.htaccess +++ b/.htaccess @@ -1 +1,5 @@ -FallbackResource /DirektiveDesDons/index.php \ No newline at end of file +# Redirect everything to index.php +RewriteEngine on +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteRule ^.*$ /DirektiveDesDons/index.php [L,QSA] \ No newline at end of file diff --git a/BancaDati.sql b/BancaDati.sql index fc74c0f..512a69b 100644 --- a/BancaDati.sql +++ b/BancaDati.sql @@ -3,64 +3,96 @@ SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; +CREATE TABLE `folla` +( /*Menge*/ + `id` int auto_increment NOT NULL PRIMARY KEY, + `unita` varchar(200) UNIQUE NOT NULL, /*Einheit*/ + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `ingredienti` ( /*Zutaten*/ - `id` int auto_increment NOT NULL PRIMARY KEY, - `cognome` varchar(200) NOT NULL, /*Name*/ - `caloriePerCento` integer(5) NOT NULL, /*Kalorien pro Gramm*/ - `ilPeso` integer(5) NULL, /*Gewicht*/ - `prezzo` decimal(4, 2) NOT NULL, /*Preis*/ - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -CREATE TABLE `folla` -( /*Menge*/ - `id` int auto_increment NOT NULL PRIMARY KEY, - `unita` varchar(200) NOT NULL, /*Einheit*/ - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP + `id` int auto_increment NOT NULL PRIMARY KEY, + `cognome` varchar(200) NOT NULL, /*Name*/ + `calorie` integer(5) NOT NULL, /*Kalorien*/ + `quantita` integer(5) NOT NULL, /*Anzahl*/ + `prezzo` decimal(4, 2) NOT NULL, /*Preis*/ + `follaID` int NOT NULL, /*MengeID*/ + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `elenco` ( /*Liste*/ - `id` int auto_increment NOT NULL PRIMARY KEY, - `creatore` varchar(200) NOT NULL, /*Ersteller*/ - `coloreDiSfondo` integer(10) NOT NULL, /*Hintergrundfarbe*/ - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP + `id` int auto_increment NOT NULL PRIMARY KEY, + `utenteID` int NOT NULL, /*ErstellerID*/ + `cognome` varchar(200) NOT NULL, /*Name*/ + `coloreDiSfondo` varchar(200), /*Hintergrundfarbe*/ + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `utente` ( /*Benutzer*/ - `id` int auto_increment NOT NULL PRIMARY KEY, - `email` varchar(200) NOT NULL, /*Email*/ - `parolaDordine` varchar(255) NOT NULL, /*Passwort*/ - `nomeUtente` varchar(50) UNIQUE NOT NULL, /*Benutzernamen*/ - `gettone` varchar(255), /*Token für Session*/ - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP + `id` int auto_increment NOT NULL PRIMARY KEY, + `email` varchar(200) NOT NULL, /*Email*/ + `parolaDordine` varchar(255) NOT NULL, /*Passwort*/ + `nomeUtente` varchar(50) UNIQUE NOT NULL, /*Benutzernamen*/ + `gettone` varchar(255), /*Token für Session*/ + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `elencoIngredienti` ( /*Liste_Zutaten*/ - `id` int auto_increment NOT NULL PRIMARY KEY, - `ingredientiID` int NOT NULL, /*ZutatenID*/ - `elencoID` int NOT NULL, /*ListeID*/ - `follaID` int NOT NULL, /*MengeID*/ - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP + `id` int auto_increment NOT NULL PRIMARY KEY, + `ingredientiID` int NOT NULL, /*ZutatenID*/ + `elencoID` int NOT NULL, /*ListeID*/ + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `utenteElenco` ( /*Benutzer_Liste*/ - `id` int auto_increment NOT NULL PRIMARY KEY, - `elencoID` int NOT NULL, /*ListeID*/ - `utenteID` int NOT NULL, /*BenutzerID*/ - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP + `id` int auto_increment NOT NULL PRIMARY KEY, + `elencoID` int NOT NULL, /*ListeID*/ + `utenteID` int NOT NULL, /*BenutzerID*/ + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `elencoIngredienti` /*Liste_Zutaten*/ ADD CONSTRAINT `FK_ElencoIngredienti_Ingredienti` FOREIGN KEY (`ingredientiID`) REFERENCES `ingredienti`(`id`), /*Liste_Zutaten hat Foreignkey von Zutaten(id)*/ - ADD CONSTRAINT `FK_ElencoIngredienti_Elenco` FOREIGN KEY (`elencoID`) REFERENCES `elenco`(`id`), /*Liste_Zutaten hat Foreignkey von Liste(id)*/ - ADD CONSTRAINT `FK_ElencoIngredienti_Folla` FOREIGN KEY (`follaID`) REFERENCES `folla`(`id`); /*Liste_Zutaten hat Foreignkey von Menge(id)*/ + ADD CONSTRAINT `FK_ElencoIngredienti_Elenco` FOREIGN KEY (`elencoID`) REFERENCES `elenco`(`id`); /*Liste_Zutaten hat Foreignkey von Liste(id)*/ ALTER TABLE `utenteElenco` /*Benutzer_Liste*/ ADD CONSTRAINT `FK_UtenteElenco_Utente` FOREIGN KEY (`utenteId`) REFERENCES `utente`(`id`), /*Benutzer_Liste hat Foreignkey von Benutzer(id)*/ ADD CONSTRAINT `FK_UtenteElenco_Elenco` FOREIGN KEY (`elencoId`) REFERENCES `elenco`(`id`); /*Benutzer_Liste hat Foreignkey von Liste(id)*/ + +ALTER TABLE `ingredienti` + ADD CONSTRAINT `FK_Ingredienti_Folla` FOREIGN KEY (`follaID`) REFERENCES `folla`(`id`); /*Zutaten hat Foreignkey von Menge(id)*/ + +ALTER TABLE `elenco` + ADD CONSTRAINT `FK_Elenco_Utente` FOREIGN KEY (`utenteId`) REFERENCES `utente`(`id`); /*Liste hat Foreignkey von Benutzer(id)*/ + + + + + + +/*Test Data*/ +INSERT INTO `utente` (email, parolaDordine, nomeUtente) VALUES ('test@test.com', 'password', "testuser"); +INSERT INTO `utente` (email, parolaDordine, nomeUtente) VALUES ('test1@test.com', 'password1', "testuser1"); + + +INSERT INTO `folla` (unita) VALUES ('st'); +INSERT INTO `folla` (unita) VALUES ('g'); +INSERT INTO `folla` (unita) VALUES ('kg'); +INSERT INTO `folla` (unita) VALUES ('mg'); +INSERT INTO `folla` (unita) VALUES ('l'); +INSERT INTO `folla` (unita) VALUES ('ml'); +INSERT INTO `folla` (unita) VALUES ('TL'); +INSERT INTO `folla` (unita) VALUES ('EL'); + +INSERT INTO `ingredienti` (cognome, calorie, quantita, prezzo, follaID) VALUES ('Raffinierter Zucker', 3870, 1000, 5, 2); +INSERT INTO `ingredienti` (cognome, calorie, quantita, prezzo, follaID) VALUES ('Die Chips von der Tanke', 843, 375, 4.30, 2); + +INSERT INTO `elenco` (utenteID, cognome) VALUES (1, 'Liste den Einkauf bei Netto'); + +INSERT INTO `elencoIngredienti` (ingredientiID, elencoID) VALUES (1, 1); +INSERT INTO `elencoIngredienti` (ingredientiID, elencoID) VALUES (2, 1); diff --git a/BancaDati/BancaDati.php b/BancaDati/BancaDati.php index 9690979..24338bb 100644 --- a/BancaDati/BancaDati.php +++ b/BancaDati/BancaDati.php @@ -22,6 +22,7 @@ class BancaDati { , $this->pw , array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); } catch (PDOException $e) { + var_dump($e); die; } } @@ -54,8 +55,10 @@ class BancaDati { try { $sth = $this->pdo->prepare($sql); $sth->execute(); + return $this->pdo->lastInsertId(); }catch (PDOException $e){ - die; + return false; + //die; } } @@ -108,7 +111,7 @@ class BancaDati { * @return void * @author Malte Schulze Hobeling */ - public function select(string $table, array $where){ + public function select(string $table, array $where = []){ $whereString = ""; $orderString = ""; if(isset($where["by"])){ @@ -125,9 +128,9 @@ class BancaDati { } $whereString .= "`" . $col . "` LIKE '" . $v . "'"; } - $sql = "SELECT * FROM ".$table." WHERE ".$whereString.$orderString.";"; + $sql = "SELECT * FROM " . $table . ((count($where) > 0) ? " WHERE ".$whereString.$orderString : "") .";"; try { - return $this->pdo->query($sql)->fetch(); + return $this->pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC); }catch (PDOException $e){ die; } diff --git a/Documentation/Dokumentation.md b/Documentation/Dokumentation.md new file mode 100644 index 0000000..e34181e --- /dev/null +++ b/Documentation/Dokumentation.md @@ -0,0 +1,142 @@ +# Dokumentation + +Eine auflistung von allen Funktionen und API-Endpunkten mit Erklärung. + +- User +- Einkaufsliste +- Zutaten +- Einheiten + +--- + +## User + +### User erstellen +```shell +POST 127.0.0.1/DirektiveDesDons/user + +BODY +{ + "username": "Benutzername", + "email": "email" + "password": "Passwort", +} +``` + +### Aktueller User ausgeben +```shell +GET 127.0.0.1/DirektiveDesDons/user +``` + +### Login +```shell +POST 127.0.0.1/DirektiveDesDons/login + +BODY +{ + "username": "Benutzername", + "password": "Passwort" +} +``` + +--- + +## Einkaufsliste + +### Einkaufsliste erstellen +```shell +POST 127.0.0.1/DirektiveDesDons/list + +BODY +{ + "name": "Einkaufsliste 1" + "backgoundColor": "#123", +} +``` + +### Einkauslisten ausgeben +```shell +GET 127.0.0.1/DirektiveDesDons/list +``` + +### Einkaufsliste ausgeben +```shell +GET 127.0.0.1/DirektiveDesDons/list/1 +``` + +### Einkaufsliste löschen +```shell +DELETE 127.0.0.1/DirektiveDesDons/list/1 +``` + +### Zutat zu Einkaufsliste hinzufügen +```shell +POST 127.0.0.1/DirektiveDesDons/list/1 + +BODY +{ + "ingredientId": 1 +} +``` + +### Zutat von Liste löschen +```shell +DELETE 127.0.0.1/DirektiveDesDons/list/1/4 +``` + +--- + +## Zutaten + +### Zutaten erstellen +```shell +POST 127.0.0.1/DirektiveDesDons/ingredient + +BODY +{ + "name": "Nüsse", + "calories": "123", + "quantity": "5", + "unit": "st", + "price": "12.5" +} +``` + +### Zutaten ausgeben +```shell +GET 127.0.0.1/DirektiveDesDons/ingredient +``` + +### Zutat ausgeben +```shell +GET 127.0.0.1/DirektiveDesDons/ingredient/1 +``` + +### Zutat löschen +```shell +DELETE 127.0.0.1/DirektiveDesDons/ingredient/1 +``` + +--- + +## MengenEinheiten + +### Einheiten auflisten +```shell +GET 127.0.0.1/DirektiveDesDons/unit +``` + +### Einheit Erstellen +```shell +POST 127.0.0.1/DirektiveDesDons/unit + +BODY +{ + "name": "lbs" +} +``` + +### Einheit löschen +```shell +DELETE 127.0.0.1/DirektiveDesDons/unit/4 +``` \ No newline at end of file diff --git a/Router/Response.php b/Router/Response.php index 69065d7..8dedd7e 100644 --- a/Router/Response.php +++ b/Router/Response.php @@ -31,6 +31,7 @@ class Response http_response_code($status); } header('Content-Type: application/json; charset=utf-8'); + $data["status"] = http_response_code(); echo json_encode($data); } diff --git a/Router/Router.php b/Router/Router.php index 35d05fc..69baccd 100644 --- a/Router/Router.php +++ b/Router/Router.php @@ -20,8 +20,9 @@ class Router */ public function __construct(string $pathname) { - $this->uri = is_countable($_SERVER['REQUEST_URI']) && count($_SERVER['REQUEST_URI']) > 1 ? rtrim($_SERVER['REQUEST_URI'], "/") : $_SERVER['REQUEST_URI']; - $this->uri = str_replace($pathname, "", $this->uri); + $this->uri = str_replace($pathname, "", $_SERVER['REQUEST_URI']); + $this->uri = strlen($this->uri) > 1 ? rtrim($this->uri, "/") : $this->uri; + $this->requestType = $_SERVER['REQUEST_METHOD']; $this->routes = []; $this->middleware = []; @@ -32,7 +33,7 @@ class Router if (isset($_POST)) { $this->request["body"] = json_decode(file_get_contents('php://input'), true); } - if (isset($_POST)) { + if (isset($_GET)) { $this->request["params"] = $_GET; } @@ -235,7 +236,7 @@ class Router if ($controller) { $controller($this->request, $this->response); } else { - echo "404"; + $this->response->json(["status" => "404", "message" => "Not found"], 404); } } } \ No newline at end of file diff --git a/User.php b/User.php index 203368b..ba73a67 100644 --- a/User.php +++ b/User.php @@ -18,7 +18,7 @@ class User { return true; } public function loginWithUsername(string $username, string $password) : string { - $userObject = $this->db->select("utente", ["nomeUtente" => $username]); + $userObject = $this->db->select("utente", ["nomeUtente" => $username])[0]; if(!$userObject){ return false; @@ -38,7 +38,7 @@ class User { return $this->token; } public function loginWithToken(string $token){ - $userObject = $this->db->select("utente", ["gettone" => $token]); + $userObject = $this->db->select("utente", ["gettone" => $token])[0]; if(!$userObject){ return false; } diff --git a/index.php b/index.php index b172924..c25554e 100644 --- a/index.php +++ b/index.php @@ -2,77 +2,298 @@ require_once("Router/Router.php"); require_once("Router/Response.php"); +require_once("Router/Route.php"); require_once("BancaDati/BancaDati.php"); require_once("User.php"); use Router\Response; use Router\Router; +use Router\Route; use BancaDati\BancaDati; +abstract class HTTP_STATUS_CODE { + const OK = 200; + const CREATED = 201; + const BAD_REQUEST = 400; + const FORBIDDEN = 403; + const NOT_FOUNT = 404; +} + + $app = new Router("/DirektiveDesDons"); $db = new BancaDati(); + +/* + * Middleware + */ $app->use("/", function (array &$req, Response $res) { - if(isset($_COOKIE["TOKEN"])){ + if (isset($_COOKIE["TOKEN"])) { $user = new User(); - if($user->loginWithToken($_COOKIE["TOKEN"])){ + if ($user->loginWithToken($_COOKIE["TOKEN"])) { $req["user"] = $user; } } }); -$app->get("/", function (array $req, Response $res) { - $res->send("Hello World"); - //var_dump($req["user"]); +/* + * Home + */ +$app->get("/", function (array $req, Response $res) use ($db) { + $res->json(["message" => "", + "name" => "Shopping List", + "authors" => "Simon Bock, Johannes Kantz & Malte Schulze Hobeling"]); }); +/* + * User + */ $app->get("/user", function (array $req, Response $res) { - $res->send("user"); + if (isset($req["user"])) { + $res->json(["id" => $req["user"]->id, "username" => $req["user"]->username, "email" => $req["user"]->email]); + } else { + $res->json(["status" => HTTP_STATUS_CODE::FORBIDDEN, "message" => "You are not logged in. Goto '/login' to login"]); + } }); $app->get("/user/:id", function (array $req, Response $res) use ($db) { $db->select("utente", ["username" => $req["id"]]); $res->send("user " . $req["params"]["id"]); }); -$app->post("/createuser", function (array $req, Response $res) use ($db) { +$app->post("/signup", function (array $req, Response $res) use ($db) { $newUsername = $req["body"]["username"]; $newPassword = $req["body"]["password"]; $newEmail = $req["body"]["email"]; - // $db->insert("utente", ["email" => "test@email.com", "parolaDordine" => "password", "nomeUtente" => "testuser"]); $db->insert("utente", ["email" => "$newEmail", "parolaDordine" => "$newPassword", "nomeUtente" => "$newUsername"]); - $res->send("user "); + $res->send("Account Created", HTTP_STATUS_CODE::CREATED); }); -$app->post("/login", function( array $req, Response $res) use ($db) { +$app->post("/login", function (array $req, Response $res) use ($db) { $username = $req["body"]["username"]; $password = $req["body"]["password"]; $user = new User(); $usertoken = $user->loginWithUsername($username, $password); - if($usertoken){ - setcookie("TOKEN", $usertoken, time()+3600); // 1h - $res->send("Login successful" . "token: " . $usertoken, 200); - }else{ - $res->send("Login failed", 403); + if ($usertoken) { + setcookie("TOKEN", $usertoken, time() + 3600); // 1h + $res->json(["message" => "Login successful", "token" => $usertoken]); + } else { + $res->json(["message" => "Login failed"], HTTP_STATUS_CODE::FORBIDDEN); } }); -$app->post("/createingredients", function (array $req, Response $res) use ($db) { - $newIngredient = $req["body"]["ingredient"]; - $newCalorie = $req["body"]["calories"]; - $newWeight = $req["body"]["weight"]; - $newPrice = $req["body"]["price"]; - $db->insert("ingredienti", ["cognome" => "$newIngredient", "caloriePerCento" => "$newCalorie", "ilPeso" => "$newWeight", "prezzo" => "$newPrice"]); +/* + * Ingredients + */ +$app->route("/ingredient") + ->get(function (array $req, Response $res) use ($db) { + $res->json(["data" => $db->select("ingredienti")]); + }) + ->post(function (array $req, Response $res) use ($db) { + $name = $req["body"]["name"]; + $calories = $req["body"]["calories"]; + $quantity = $req["body"]["quantity"]; + $unit = $req["body"]["unit"]; + $price = $req["body"]["price"]; - $res->send("New ingredient has been listed "); + $unitInTable = $db->select("folla", ["unita" => $unit]); + if (count($unitInTable) > 1) { + $res->json(["message" => "Unit: " . $unit . " does not exist. Please create unit first"], HTTP_STATUS_CODE::BAD_REQUEST); + return; + } + $unitId = $unitInTable[0]["id"]; + + $id = $db->insert("ingredienti", ["cognome" => "$name", "calorie" => "$calories", "quantita" => "$quantity", "follaID" => $unitId, "prezzo" => "$price"]); + if (!$id) { + $res->json(["message" => "Something went wrong when creating the Ingredient"], HTTP_STATUS_CODE::BAD_REQUEST); + return; + } + + $res->json(["message" => "New ingredient has been listed", + "ingredient" => $db->select("ingredienti", ["id" => $id])]); + }); +$app->route("/ingredient/:id") + ->get(function (array $req, Response $res) use ($db) { + $id = $req["params"]["id"]; + $ingredient = $db->select("ingredienti", ["id" => $id])[0]; + $res->json(["data" => $ingredient]); + }) + ->put(function (array $req, Response $res) use ($db) { + $id = $req["params"]["id"]; + + $name = $req["body"]["name"]; + $calories = $req["body"]["calories"]; + $quantity = $req["body"]["quantity"]; + $unit = $req["body"]["unit"]; + $price = $req["body"]["price"]; + + $unitInTable = $db->select("folla", ["unita" => $unit]); + if (count($unitInTable) > 1) { + $res->json(["message" => "Unit: " . $unit . " does not exist. Please create unit first"], HTTP_STATUS_CODE::BAD_REQUEST); + return; + } + $unitId = $unitInTable[0]["id"]; + + $db->update("ingredienti", $id, ["cognome" => "$name", "calorie" => "$calories", "quantita" => "$quantity", "follaID" => $unitId, "prezzo" => "$price"]); + + $res->json(["message" => "Ingredient has been updated", "data" => $db->select("ingredienti", ["id" => $id])[0]]); + }) + ->delete(function (array $req, Response $res) use ($db) { + $id = $req["params"]["id"]; + $db->delete("ingredienti", $id); + $res->json(["message" => "Ingredient has been deleted"]); + }); + +/* + * Unit + */ +$app->route("/unit") + ->get(function (array $req, Response $res) use ($db) { + $res->json(["data" => $db->select("folla")]); + }) + ->post(function (array $req, Response $res) use ($db) { + $name = $req["body"]["name"]; + + if (!isset($name) || strlen($name) < 1 || strlen($name) > 200) { + $res->json(["message" => "Invalid Request. Please follow the Documentation", HTTP_STATUS_CODE::BAD_REQUEST]); + return; + } + + $selectWithSameName = $db->select("folla", ["unita" => $name]); + if (count($selectWithSameName) >= 1) { + $res->json(["message" => "Unit: " . $name . " already exists", "data" => $selectWithSameName[0]], HTTP_STATUS_CODE::BAD_REQUEST); + return; + } + + $newUnitId = $db->insert("folla", ["unita" => $name]); + $res->json(["message" => "Unit: '" . $name . "' created", "data" => $db->select("folla", ["id" => $newUnitId])[0]], HTTP_STATUS_CODE::CREATED); + }); +$app->route("/unit/:id") + ->get(function (array $req, Response $res) use ($db) { + $id = $req["params"]["id"]; + $ingredient = $db->select("folla", ["id" => $id])[0]; + $res->json(["data" => $ingredient]); + }) + ->put(function (array $req, Response $res) use ($db) { + $id = $req["params"]["id"]; + $name = $req["body"]["name"]; + + if (!isset($name) || strlen($name) < 1 || strlen($name) > 200) { + $res->json(["message" => "Invalid Request. Please follow the Documentation", HTTP_STATUS_CODE::BAD_REQUEST]); + return; + } + $db->update("folla", $id, ["unita" => $name]); + $res->json(["message" => "Unit has been updated", "data" => $db->select("folla", ["id" => $id])]); + }) + ->delete(function (array $req, Response $res) use ($db) { + $id = $req["params"]["id"]; + $db->delete("folla", $id); + $res->json(["message" => "Unit has been deleted"]); + }); + +/* + * List + */ +$app->use("/list", function (array $req, Response $res) { + if (!isset($req["user"])) { + $res->json(["message" => "You need to be signed in to use lists"], HTTP_STATUS_CODE::FORBIDDEN); + die; + } }); -$app->post("/createunits", function (array $req, Response $res) use ($db) { - $newUnit = $req["body"]["unit"]; - $db->insert("folla", ["unita" => "$newUnit"]); +$app->route("/list") + ->get(function (array $req, Response $res) use ($db) { + $lists = $db->select("elenco", ["utenteID" => $req["user"]->id]); + // add items to list + foreach ($lists as &$list) { + $listId = $list["id"]; + $ingredients = $db->select("elencoIngredienti", ["elencoId" => $listId]); + $ingredientData = []; + foreach ($ingredients as &$ingredient) { + $ingredientData[] = $db->select("Ingredienti", ["id" => $ingredient["ingredientiID"]]); + } + $list["inredients"] = $ingredientData; + } + $res->json(["data" => $lists]); + }) + ->post(function (array $req, Response $res) use ($db) { + $name = $req["body"]["name"]; + $bgColor = $req["body"]["backgoundColor"] ?? "#fff"; - $res->send("New unit has been listed "); + if (!isset($name) || strlen($name) < 1) { + $res->json(["message" => "Invalid Request. Please follow the Documentation"], HTTP_STATUS_CODE::BAD_REQUEST); + return; + } + + $lastListId = $db->insert("elenco", ["cognome" => $name, "coloreDiSfondo" => $bgColor, "utenteID" => $req["user"]->id]); + $res->json(["message" => "New List '" . $name . "' created", "data" => $db->select("elenco", ["id" => $lastListId])], HTTP_STATUS_CODE::CREATED); + }); +$app->route("/list/:id") + ->get(function (array $req, Response $res) use ($db) { + $id = $req["params"]["id"]; + $query = $db->select("elenco", ["id" => $id, "utenteID" => $req["user"]->id]); + + if (count($query) < 1) { + $res->json(["message" => "List does not exists or you dont have permissions to view it"]); + return; + } + $list = $query[0]; + + $listId = $list["id"]; + $ingredients = $db->select("elencoIngredienti", ["elencoId" => $listId]); + $ingredientData = []; + foreach ($ingredients as &$ingredient) { + $ingredientData[] = $db->select("Ingredienti", ["id" => $ingredient["ingredientiID"]]); + } + $list["inredients"] = $ingredientData; + + $res->json(["data" => $list]); + }) + ->post(function (array $req, Response $res) use ($db) { + $id = $req["params"]["id"]; + $ingredientId = $req["body"]["ingredientId"]; + + if (!isset($ingredientId)) { + $res->json(["message" => "You need to set a valid 'ingredientId'", HTTP_STATUS_CODE::BAD_REQUEST]); + return; + } + + $newId = $db->insert("elencoIngredienti", ["ingredientiID" => $ingredientId, "elencoID" => $id]); + if(!$newId){ + $res->json(["message" => "Cannot insert item in list"], HTTP_STATUS_CODE::BAD_REQUEST); + return; + } + $res->json(["message" => "Item has been added"]); + }) + ->delete(function (array $req, Response $res) use ($db) { + $id = $req["params"]["id"]; + + $list = $db->select("elenco", ["id" => $id]); + if (count($list) < 1) { + $res->json(["message" => "List does not exist"]); + return; + } + if ($list[0]["utenteID"] != $req["user"]->id) { + $res->json(["message" => "You have no permissions the delete this list"], HTTP_STATUS_CODE::FORBIDDEN); + return; + } + + $db->delete("elenco", $id); + $res->json(["message" => "List has been deleted"]); + }); +$app->delete("/list/:id/:item", function (array $req, Response $res) use ($db) { + $listId = $req["params"]["id"]; + $itemId = $req["params"]["item"]; + + $list = $db->select("elenco", ["id" => $listId, "utenteID" => $req["user"]->id]); + if(count($list) < 1){ + $res->json(["message" => "List does not exist or you dont have the permissions to edit the list"]); + return; + } + + $db->delete("elencoIngredienti", $itemId); + $res->json(["message" => "Item has been deleted"]); }); $app->start(); \ No newline at end of file