34786-vm/handle_agregar_producto.php
2025-12-12 16:33:10 +00:00

73 lines
2.8 KiB
PHP

<?php
session_start();
if (!isset($_SESSION["user_id"])) {
header("Location: auth/login.php");
exit();
}
require_once 'db/config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Sanitize and retrieve product data
$nombre = filter_input(INPUT_POST, 'nombre', FILTER_SANITIZE_STRING);
$descripcion = filter_input(INPUT_POST, 'descripcion', FILTER_SANITIZE_STRING);
$costo = filter_input(INPUT_POST, 'costo', FILTER_VALIDATE_FLOAT);
$precio_venta = filter_input(INPUT_POST, 'precio_venta', FILTER_VALIDATE_FLOAT);
// Retrieve stock data array
$stocks_por_ciudad = isset($_POST['stock_ciudad']) ? $_POST['stock_ciudad'] : [];
// Basic validation
if ($nombre && $costo !== false && $precio_venta !== false) {
$pdo = db();
try {
$pdo->beginTransaction();
// 1. Insert product
$sku = 'SKU-' . strtoupper(substr(uniqid(), -8));
$sql_producto = "INSERT INTO productos (sku, nombre, descripcion, costo, precio_venta, created_at) VALUES (?, ?, ?, ?, ?, NOW())";
$stmt_producto = $pdo->prepare($sql_producto);
$stmt_producto->execute([$sku, $nombre, $descripcion, $costo, $precio_venta]);
// Get the ID of the new product
$producto_id = $pdo->lastInsertId();
// 2. Insert stock for each city
$sql_stock = "INSERT INTO stock_por_ciudad (producto_id, ciudad_id, stock_actual) VALUES (?, ?, ?)";
$stmt_stock = $pdo->prepare($sql_stock);
foreach ($stocks_por_ciudad as $ciudad_id => $cantidad) {
$ciudad_id_int = filter_var($ciudad_id, FILTER_VALIDATE_INT);
$cantidad_int = filter_var($cantidad, FILTER_VALIDATE_INT);
// Only insert if stock is greater than 0 and IDs are valid
if ($ciudad_id_int && $cantidad_int > 0) {
$stmt_stock->execute([$producto_id, $ciudad_id_int, $cantidad_int]);
}
}
// If all is well, commit the transaction
$pdo->commit();
$_SESSION['success_message'] = "Producto y stock por ciudad agregados exitosamente.";
} catch (PDOException $e) {
// If something goes wrong, roll back the transaction
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
// Log error properly in a real application
$_SESSION['error_message'] = "Error al agregar el producto. Detalles: " . $e->getMessage();
}
} else {
$_SESSION['error_message'] = "Datos de producto inválidos. Por favor, revisa el formulario.";
}
} else {
$_SESSION['error_message'] = "Método no permitido.";
}
// Redirect back to the products page
header("Location: productos.php");
exit();