IFCD0210/Practicas/Practicas_SQL/ejercicios/tienda/realizar_pedido.php
2024-03-20 13:43:42 +01:00

171 lines
6.5 KiB
PHP

<?php
session_start();
if (!isset($_SESSION['cliente_id'])) {
header('Location: login.php');
die();
}
$cliente_id = $_SESSION['cliente_id'];
$nombre_servidor = "localhost";
$nombre_usuario = "root";
$contraseña = "Logomark8";
$nombre_base_datos = "tienda";
mysqli_report(MYSQLI_REPORT_OFF);
$conexion = mysqli_connect($nombre_servidor, $nombre_usuario, $contraseña, $nombre_base_datos);
if (!$conexion) {
exit("Error de conexión: " . mysqli_connect_error());
}
$consulta_sql = "SELECT * FROM productos";
$resultado = mysqli_query($conexion, $consulta_sql);
if (!$resultado) {
exit("Error al ejecutar la consulta: " . mysqli_error($conexion));
}
$productos = mysqli_fetch_all($resultado, MYSQLI_ASSOC);
mysqli_free_result($resultado);
mysqli_close($conexion);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="estilo.css">
<title>Registro Pedidos</title>
</head>
<body>
<h2>Registrar Pedido</h2>
<div style="display: flex; flex-direction: row; gap:1rem;">
<form style="display: inline-block; width: 100%;" action="" method="post">
<table>
<tr>
<th>Descripcion</th>
<th>Precio</th>
<th>Cantidad</th>
</tr>
<?php
foreach ($productos as $producto) {
echo "<tr>";
echo "<td>$producto[nombre] </td> <td style='text-align: right;'>$producto[precio] € </td>";
echo "<td hidden> <input type='text' id='producto_nombre' name='producto_nombre[]'value='$producto[nombre]'></td>";
echo "<td hidden> <input type='number' id='producto_id' name='producto_id[]'value=$producto[producto_id]></td>";
echo "<td hidden> <input type='number' id='precio' name='precio[]' value=$producto[precio]></td>";
echo "<td> <input style='text-align: right;' type='number' id='cantidad' name='cantidad[]' value=0 min='0'></td>";
echo "</tr>";
}
?>
</table>
<br>
<input type="submit" name="registrar" value="Registrar Pedido">
</form>
<?php muestraPedido() ?>
</div>
</body>
<?php
function muestraPedido()
{
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['registrar']) && (array_sum($_POST['cantidad']) !== 0)) {
$lineas_pedido = array();
$total_pedido = 0;
foreach (array_keys($_POST['producto_id']) as $index) {
if ($_POST['cantidad'][$index] > 0) {
$lineas_pedido[] = array(
'nombre' => $_POST['producto_nombre'][$index],
'producto_id' => intval($_POST['producto_id'][$index]),
'cantidad' => intval($_POST['cantidad'][$index]),
'precio' => floatval($_POST['precio'][$index]),
'total_linea' => $_POST['cantidad'][$index] * $_POST['precio'][$index]
);
$total_pedido += $_POST['cantidad'][$index] * $_POST['precio'][$index];
}
}
echo "
<form style='display: inline-block; width: 100%;' action='' method='post'>
<table style='width:100%'>
<tr>
<th>Id</th>
<th>Descripcion</th>
<th>Cantidad</th>
<th>Precio Uni.</th>
<th>Total linea</th>
</tr>";
foreach ($lineas_pedido as $linea) {
echo "<tr>";
echo "<td>$linea[producto_id]</td><td>$linea[nombre]</td> <td style='text-align: right;'>$linea[cantidad]</td> <td style='text-align: right;'>$linea[precio] €</td> <td style='text-align: right;'>$linea[total_linea] €</td>";
echo "<td hidden> <input type='number' id='producto_id' name='producto_id[]'value=$linea[producto_id]></td>";
echo "<td hidden> <input type='number' id='precio' name='precio[]' value=$linea[precio]></td>";
echo "<td hidden> <input type='number' id='cantidad' name='cantidad[]' value=$linea[cantidad]></td>";
echo "</tr>";
}
echo "<tr><td colspan=3></td><td style='text-align: right;'>Total: </td><td style='text-align: right;'>$total_pedido €</td></tr>";
echo "</table>
<br>
<input type='submit' name='confirmar' value='Confirmar Pedido'>
</form>
";
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['confirmar'])) {
$lineas_pedido = array();
$total_pedido = 0;
foreach (array_keys($_POST['producto_id']) as $index) {
if ($_POST['cantidad'][$index] > 0) {
$lineas_pedido[] = array(
'producto_id' => intval($_POST['producto_id'][$index]),
'cantidad' => intval($_POST['cantidad'][$index]),
'precio' => floatval($_POST['precio'][$index]),
'total_linea' => $_POST['cantidad'][$index] * $_POST['precio'][$index]
);
$total_pedido += $_POST['cantidad'][$index] * $_POST['precio'][$index];
}
}
$cliente_id = $_SESSION['cliente_id'];
$nombre_servidor = "localhost";
$nombre_usuario = "root";
$contraseña = "Logomark8";
$nombre_base_datos = "tienda";
mysqli_report(MYSQLI_REPORT_OFF);
$conexion = mysqli_connect($nombre_servidor, $nombre_usuario, $contraseña, $nombre_base_datos);
if (!$conexion) {
exit("Error de conexión: " . mysqli_connect_error());
}
$estado_pedido = "pendiente";
$consulta_pedido = "INSERT INTO pedidos (cliente_id, fecha, estado, total) VALUES ('$cliente_id', NOW(), '$estado_pedido','$total_pedido')";
if (!mysqli_query($conexion, $consulta_pedido)) {
exit("Error al registrar el pedido: " . mysqli_error($conexion));
} else {
$pedido_id = mysqli_insert_id($conexion);
foreach ($lineas_pedido as $linea) {
$producto_id = $linea['producto_id'];
$cantidad = $linea['cantidad'];
$precio_unitario = $linea['precio'];
$consulta_detalles = "INSERT INTO detalles_pedido (pedido_id, producto_id, cantidad, precio_unitario) VALUES ('$pedido_id', '$producto_id', '$cantidad', '$precio_unitario')";
if (!mysqli_query($conexion, $consulta_detalles)) {
exit("Error al registrar los detalles del pedido: " . mysqli_error($conexion));
}
}
echo "<p>El pedido ha sido registrado correctamente</p>";
}
mysqli_close($conexion);
}
?>
</html>