Commit a432d5ea by Juan Montilla

Recetas sincronizadas con la página y vista receta

parent 63d94844
...@@ -44,6 +44,7 @@ $routes->get('login','Pages::viewLogin'); ...@@ -44,6 +44,7 @@ $routes->get('login','Pages::viewLogin');
$routes->get('users','User::list'); $routes->get('users','User::list');
$routes->get('home','Pages::prueba'); $routes->get('home','Pages::prueba');
$routes->get('(:segment)', 'Home::index'); $routes->get('(:segment)', 'Home::index');
$routes->get('/recipe/(:num)', 'RecipesController::view_recipe/$1');
/* /*
......
<?php
namespace App\Controllers;
use App\Models\RecipesModel;
use CodeIgniter\Controller;
class RecipesController extends Controller
{
public function view_recipe($recipe_id)
{
$recipesModel = new RecipesModel();
$recipe = $recipesModel->find($recipe_id);
$ingredients = $recipesModel->get_recipe_ingredients($recipe_id);
if ($recipe == null) {
// Mostrar un mensaje de error si no se encuentra la receta
return redirect()->to('/');
}
$data = [
'recipe' => $recipe,
'ingredients' => $ingredients,
];
return view('templates/header',$data)
.view('pages/recipe_view', $data)
. view('templates/footer');
}
}
...@@ -41,7 +41,10 @@ class User extends BaseController ...@@ -41,7 +41,10 @@ class User extends BaseController
//"rules" => "required|min_length[8]|max_length[20]" //"rules" => "required|min_length[8]|max_length[20]"
] ]
]; ];
$session = session(); $session = session();
$userModel = model('UserModel');
if ($this->request->getMethod() == "post") { if ($this->request->getMethod() == "post") {
if ($this->validate($rules)) { if ($this->validate($rules)) {
$email = $this->request->getVar('email'); $email = $this->request->getVar('email');
...@@ -74,7 +77,12 @@ class User extends BaseController ...@@ -74,7 +77,12 @@ class User extends BaseController
} }
public function user_ok() public function user_ok()
{ {
return view('templates/header') $session = session();
$usuario = $session->__get('user');
$data['usuario'] = $usuario;
$userModel = model('UserModel');
return view('templates/header',$data)
. view('pages/home') . view('pages/home')
. view('templates/footer'); . view('templates/footer');
} }
...@@ -93,63 +101,67 @@ class User extends BaseController ...@@ -93,63 +101,67 @@ class User extends BaseController
} }
public function registerAjax() public function registerAjax()
{ {
$validation = \Config\Services::validation(); $validation = \Config\Services::validation();
$rules = [ $rules = [
"username" => [ "username" => [
"label" => "Username", "label" => "Username",
"rules" => "required" "rules" => "required"
], ],
"email" => [ "email" => [
"label" => "Email", "label" => "Email",
"rules" => "required|valid_email|is_unique[user.email]" "rules" => "required|valid_email|is_unique[user.email]"
], ],
"password" => [ "password" => [
"label" => "Password", "label" => "Password",
"rules" => "required|min_length[8]|max_length[20]" "rules" => "required|min_length[8]|max_length[20]"
] ]
]; ];
$data = []; $data = [];
$session = session();
$userModel = model('UserModel'); $session = session();
if ($this->request->getMethod() == "post") { $userModel = model('UserModel');
if ($this->validate($rules)) {
// Código de registro y respuesta exitosa if ($this->request->getMethod() == "post") {
$username = $this->request->getVar('username'); if ($this->validate($rules)) {
$email = $this->request->getVar('email'); // Código de registro y respuesta exitosa
$password = $this->request->getVar('password'); $name = $this->request->getVar('username');
$user = [ $email = $this->request->getVar('email');
'username' => $username, $password = $this->request->getVar('password');
'email' => $email, $userData = [
'password' => password_hash($password, PASSWORD_DEFAULT), 'username' => $name,
]; 'email' => $email,
$userModel->saveUser($email, $username, $password); 'password' => password_hash($password, PASSWORD_DEFAULT),
$session->set('logged_in', TRUE); ];
$session->set('user', $user); $userModel->saveUser($email, $name, $password);
return $this->response->setStatusCode(200)->setJSON([ $newUser = $userModel->authenticate($email, $password);
'text' => 'Usuario logeado' $session->set('logged_in', TRUE);
]); $session->set('user', $newUser);
} else {
$error_message = ''; return $this->response->setStatusCode(200)->setJSON([
'text' => 'Usuario logeado'
if ($validation->getError('email')) { ]);
$error_message = 'Email ya en uso o inválido';
} elseif ($validation->getError('password')) {
$error_message = 'La contraseña debe tener entre 8 y 20 caracteres';
} else { } else {
$error_message = 'Error desconocido'; $error_message = '';
}
if ($validation->getError('email')) {
$error_message = 'Email ya en uso o inválido';
} elseif ($validation->getError('password')) {
$error_message = 'La contraseña debe tener entre 8 y 20 caracteres';
} else {
$error_message = 'Error desconocido';
}
return $this->response->setStatusCode(400)->setJSON([ return $this->response->setStatusCode(400)->setJSON([
'text' => $error_message 'text' => $error_message
]); ]);
}
} }
}
return $this->response->setStatusCode(400)->setJSON([ return $this->response->setStatusCode(400)->setJSON([
'text' => 'Solo se aceptan post request' 'text' => 'Solo se aceptan post request'
]); ]);
} }
......
<?php
namespace App\Models;
use CodeIgniter\Model;
class IngredientModel extends Model
{
protected $table = 'ingredient';
protected $primaryKey = 'id';
protected $useAutoIncrement = true; # db takes care of it
protected $returnType = 'object'; # 'object' or 'array'
protected $useSoftDeletes = false; # true if you expect to recover data
# Fields that can be set during save, insert, or update methods
protected $allowedFields = ['id', 'name', 'icon'];
protected $useTimestamps = false; # no timestamps on inserts and updates
# Do not use validations rules (for the time being...)
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
public function saveRecipe($id, $name, $icon)
{
$data = [
'id' => $id,
'name' => $name,
'icon' => $icon,
];
return $this->insert($data);
}
}
\ No newline at end of file
<?php
namespace App\Models;
use CodeIgniter\Model;
class RecipesIngredientModel extends Model
{
protected $table = 'recipes_ingredient';
protected $primaryKey = 'id';
protected $useAutoIncrement = true; # db takes care of it
protected $returnType = 'object'; # 'object' or 'array'
protected $useSoftDeletes = false; # true if you expect to recover data
# Fields that can be set during save, insert, or update methods
protected $allowedFields = ['id', 'amount', 'id_recipe','id_ingredient'];
protected $useTimestamps = false; # no timestamps on inserts and updates
# Do not use validations rules (for the time being...)
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
public function saveRecipe($id, $amount, $id_recipe, $id_ingredient)
{
$data = [
'id' => $id,
'amount' => $amount,
'id_recipe' => $id_recipe,
'id_ingredient' => $id_ingredient,
];
return $this->insert($data);
}
}
\ No newline at end of file
<?php
namespace App\Models;
use CodeIgniter\Model;
class recipesModel extends Model
{
protected $table = 'recipes';
protected $primaryKey = 'id';
protected $useAutoIncrement = true; # db takes care of it
protected $returnType = 'object'; # 'object' or 'array'
protected $useSoftDeletes = false; # true if you expect to recover data
# Fields that can be set during save, insert, or update methods
protected $allowedFields = ['id', 'name', 'season','origin','photo','is_vegan','description','instructions','link'];
protected $useTimestamps = false; # no timestamps on inserts and updates
# Do not use validations rules (for the time being...)
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
public function saveRecipe($id, $name, $season, $origin, $photo, $is_vegan, $description, $instructions, $link)
{
$data = [
'id' => $id,
'name' => $name,
'season' => $season,
'origin' => $origin,
'photo' => $photo,
'is_vegan' => $is_vegan,
'description' => $description,
'instructions' => $instructions,
'link' => $link,
];
return $this->insert($data);
}
public function get_recipe_ingredients($recipe_id) {
$builder = $this->db->table('recipes_ingredient');
$builder->select('ingredient.name, ingredient.icon, recipes_ingredient.amount');
$builder->join('ingredient', 'recipes_ingredient.id_ingredient = ingredient.id');
$builder->where('recipes_ingredient.id_recipe', $recipe_id);
$query = $builder->get();
return $query->getResult();
}
}
\ No newline at end of file
<?php
function getYoutubeVideoId($url) {
$pattern = '/^(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i';
preg_match($pattern, $url, $matches);
return isset($matches[1]) ? $matches[1] : null;
}
?>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.container {
max-width: 960px;
margin: 0 auto;
padding: 20px;
}
.recipe-header {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 30px;
}
.recipe-header img {
width: 100%;
max-width: 600px;
height: auto;
object-fit: cover;
border-radius: 8px;
}
.ingredient-list {
display: flex;
flex-wrap: wrap;
list-style-type: none;
padding: 0;
margin: 0;
margin-bottom: 30px;
}
.ingredient-item {
display: flex;
align-items: center;
width: 50%;
padding: 5px 0;
}
.ingredient-item img {
width: 30px;
height: 30px;
margin-right: 10px;
}
.instructions {
white-space: pre-line;
}
.video-container {
position: relative;
padding-bottom: 56.25%; /* Relación de aspecto 16:9 */
height: 0;
overflow: hidden;
}
.video-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
<div class="container">
<div class="recipe-header">
<h1> a</h1>
<h1><?php echo $recipe->name; ?></h1>
<img src="../imagenes/platos/<?php echo $recipe->photo; ?>" alt="<?php echo $recipe->name; ?>" />
</div>
<p><?php echo $recipe->description; ?></p>
<h2>Ingredientes</h2>
<ul class="ingredient-list">
<?php foreach ($ingredients as $ingredient) { ?>
<li class="ingredient-item">
<img src="../imagenes/ingredientes/<?php echo $ingredient->icon; ?>" alt="<?php echo $ingredient->name; ?>" />
<span><?php echo $ingredient->name; ?>: <?php echo $ingredient->amount; ?></span>
</li>
<?php } ?>
</ul>
<h2>Instrucciones</h2>
<p class="instructions"><?php echo $recipe->instructions; ?></p>
<?php if (!empty($recipe->link)): ?>
<?php $videoId = getYoutubeVideoId($recipe->link); ?>
<?php if ($videoId): ?>
<h2>Video de la receta</h2>
<div class="video-container">
<iframe width="560" height="315" src="https://www.youtube.com/embed/<?php echo $videoId; ?>" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
<?php endif; ?>
<?php endif; ?>
</div>
...@@ -216,7 +216,15 @@ ...@@ -216,7 +216,15 @@
<ul class="dropdown-menu dropdown-menu-end dropdown-menu-arrow profile"> <ul class="dropdown-menu dropdown-menu-end dropdown-menu-arrow profile">
<li class="dropdown-header"> <li class="dropdown-header">
<h6>Bob Esponja</h6> <h6>
<?php
if( isset($usuario) ){
echo $usuario->username;
}else{
echo "Usuario sin registrar";
}
?>
</h6>
</li> </li>
<li> <li>
<hr class="dropdown-divider"> <hr class="dropdown-divider">
......
...@@ -873,6 +873,17 @@ h6 { ...@@ -873,6 +873,17 @@ h6 {
color: #4154f1; color: #4154f1;
} }
.imagen-container img {
margin-left: 0;
padding-left: 0;
}
.recipe-card-link {
display: block;
text-decoration: none;
color: inherit;
}
.dashboard .news p { .dashboard .news p {
font-size: 14px; font-size: 14px;
color: #777777; color: #777777;
......
No preview for this file type
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment