diff --git a/apps/Ajax/ajax-actions.php b/apps/Ajax/ajax-actions.php index 15945d5..3834500 100644 --- a/apps/Ajax/ajax-actions.php +++ b/apps/Ajax/ajax-actions.php @@ -3,7 +3,8 @@ use Lycoreco\Apps\Recipes\Models\{ IngredientModel, RecipeModel, - RecipeUserMenu + RecipeUserMenu, + FavoriteModel }; function get_ajax_error($message, $error_code = 500) @@ -133,5 +134,57 @@ function ajax_search_ingredient() $result['count'] = count($ingredients); $result['result'] = $ingredients; + return $result; +} + +function ajax_favorites() +{ + $recipe_id = $_POST['recipe_id'] ?? null; + $type = $_POST['type'] ?? 'add'; // add, remove + + if (!CURRENT_USER) { + return get_ajax_error('You are not authorized', 401); + } + if (!isset($recipe_id)) { + return get_ajax_error("Missing 'recipe_id' parameter.", 400); + } + if($type != 'add' && $type != 'remove') + { + return get_ajax_error("'type' parameter can be only 'add' or 'remove'", 400); + } + $result = array(); + + $favorite = FavoriteModel::get(array( + [ + 'name' => 'obj.recipe_id', + 'type' => '=', + 'value' => $recipe_id + ], + [ + 'name' => 'obj.user_id', + 'type' => '=', + 'value' => CURRENT_USER->get_id() + ] + )); + + if($type == 'remove') { + if($favorite) { + $favorite->delete(); + $result['success'] = 'This recipe was removed from your favorite list'; + return $result; + } + else { + return get_ajax_error("This recipe in your favorite list is not exists", 400); + } + } + + if(!$favorite) + $favorite = new FavoriteModel(); + + $favorite->field_user_id = CURRENT_USER->get_id(); + $favorite->field_recipe_id = $recipe_id; + $favorite->save(); + + $result['success'] = 'You have successfully added recipe in your favorite list'; return $result; } \ No newline at end of file diff --git a/apps/Recipes/Models/FavoriteModel.php b/apps/Recipes/Models/FavoriteModel.php new file mode 100644 index 0000000..49e9eac --- /dev/null +++ b/apps/Recipes/Models/FavoriteModel.php @@ -0,0 +1,47 @@ + 'int', + 'recipe_id' => 'int', + 'user_id' => 'int', + ]; + + public static function init_table() + { + $result = db_query('CREATE TABLE ' . static::$table_name . ' ( + id INT AUTO_INCREMENT PRIMARY KEY, + + recipe_id INT NOT NULL, + user_id INT NOT NULL, + + FOREIGN KEY (recipe_id) REFERENCES recipes(id) ON DELETE CASCADE, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + );'); + return $result; + } + + public function valid() + { + $recipe = RecipeModel::get(array( + [ + 'name' => 'obj.id', + 'type' => '=', + 'value' => $this->field_recipe_id + ] + )); + if(!$recipe) + return ['Recipe is not exists']; + + return true; + } +} \ No newline at end of file