76 lines
2.5 KiB
PHP
76 lines
2.5 KiB
PHP
<?php
|
|
include("../db.php");
|
|
|
|
if (!isset($_SESSION['rol']) || $_SESSION['rol'] !== 'admin') {
|
|
header("Location: ../login.php?error=acceso_denegado");
|
|
exit();
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['archivo_csv'])) {
|
|
|
|
$ruta_temporal = $_FILES['archivo_csv']['tmp_name'];
|
|
$archivo = fopen($ruta_temporal, "r");
|
|
|
|
if ($archivo !== FALSE) {
|
|
fgetcsv($archivo, 1000, ";");
|
|
|
|
$importados = 0;
|
|
$errores = 0;
|
|
|
|
$stmt = $conexion->prepare("
|
|
INSERT INTO productos (id, nombre, precio, categoria, imagen, activo, stock)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
ON DUPLICATE KEY UPDATE
|
|
nombre = VALUES(nombre),
|
|
precio = VALUES(precio),
|
|
categoria = VALUES(categoria),
|
|
imagen = VALUES(imagen),
|
|
activo = VALUES(activo),
|
|
stock = VALUES(stock)
|
|
");
|
|
|
|
while (($datos = fgetcsv($archivo, 1000, ";")) !== FALSE) {
|
|
|
|
// Protección por si viene una fila vacía al final del CSV
|
|
if(count($datos) < 5) continue;
|
|
|
|
$id = trim($datos[0]);
|
|
$nombre = trim($datos[1]);
|
|
$precio = trim($datos[2]);
|
|
$categoria = trim($datos[3]);
|
|
$imagen = trim($datos[4]);
|
|
|
|
$activo = isset($datos[5]) ? trim($datos[5]) : 1;
|
|
$stock = (isset($datos[6]) && trim($datos[6]) !== '') ? trim($datos[6]) : 0;
|
|
|
|
if (empty($nombre) || empty($categoria) || !is_numeric($precio) || (float)$precio <= 0 || !is_numeric($stock) || (int)$stock < 0) {
|
|
$errores++;
|
|
continue;
|
|
}
|
|
|
|
$stock = (int)$stock;
|
|
|
|
$stmt->bind_param("isdssii", $id, $nombre, $precio, $categoria, $imagen, $activo, $stock);
|
|
|
|
if ($stmt->execute()) {
|
|
$importados++;
|
|
} else {
|
|
$errores++;
|
|
}
|
|
}
|
|
|
|
fclose($archivo);
|
|
|
|
if ($errores == 0 && $importados > 0) {
|
|
header("Location: inventario.php?status=ok_csv&cant=" . $importados);
|
|
} elseif ($importados > 0) {
|
|
header("Location: inventario.php?status=ok_csv&cant=" . $importados . "&warnings=" . $errores);
|
|
} else {
|
|
header("Location: inventario.php?status=error");
|
|
}
|
|
} else {
|
|
header("Location: inventario.php?status=error");
|
|
}
|
|
exit();
|
|
}
|
|
?>
|