Current File : /var/www/maausk-app/public/products_manage.php
<?php
// import_products.php — importación robusta de CSV a products e inventory
session_start();
require_once __DIR__ . '/db.php';

// Mostrar errores en desarrollo
ini_set('display_errors',1);
error_reporting(E_ALL);

// Verificar sesión
if (!isset($_SESSION['user_email'])) {
    header('Location: /index.php');
    exit;
}

$message = '';
$errors  = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        $message = '❌ ERROR: Subida de archivo fallida.';
    } else {
        $tmp = $_FILES['csv_file']['tmp_name'];
        if (($h = fopen($tmp, 'r')) === false) {
            $message = '❌ ERROR: No se pudo abrir el archivo.';
        } else {
            // Saltar cabecera
            fgetcsv($h, 0, ';');

            // Preparar inserción en products
            $sqlP = <<<SQL
INSERT INTO products
  (id, reference, enabled, name, ean13, price, initial_quantity)
VALUES
  (?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
  reference         = VALUES(reference),
  enabled           = VALUES(enabled),
  name              = VALUES(name),
  ean13             = VALUES(ean13),
  price             = VALUES(price),
  initial_quantity  = VALUES(initial_quantity)
SQL;
            $stmtP = $pdo->prepare($sqlP);

            // Preparar inserción en inventory
            $defaultWarehouseId = 3; // Ajusta al ID real de tu 'Almacen'
            $sqlI = <<<SQL
INSERT INTO inventory (product_id, warehouse_id, quantity)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
  quantity = VALUES(quantity)
SQL;
            $stmtI = $pdo->prepare($sqlI);

            $count = 0;
            while (($row = fgetcsv($h, 0, ';')) !== false) {
                // Asegurarnos de que hay 8 columnas
                if (count($row) < 8) {
                    $errors[] = "Fila ".($count+2)." ignorada: columnas insuficientes.";
                    continue;
                }
                list($id, $ref, $enabled, $name, $ean13, $priceIncl, $brand, $qty) = $row;

                try {
                    // Ejecutar products
                    $stmtP->execute([
                        (int)$id,
                        $ref,
                        (int)$enabled,
                        $name,
                        $ean13,
                        (float)$priceIncl,
                        (int)$qty
                    ]);
                    // Ejecutar inventory
                    $stmtI->execute([
                        (int)$id,
                        $defaultWarehouseId,
                        (int)$qty
                    ]);
                    $count++;
                } catch (Exception $e) {
                    $errors[] = "Fila ".($count+2)." error: ".$e->getMessage();
                }
            }
            fclose($h);
            $message  = "✅ Importados $count productos.";
            if ($errors) {
                $message .= "<br><small class=\"text-danger\">"
                          .implode("<br>", $errors)
                          ."</small>";
            }
        }
    }
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Importar Productos | Pharmacius</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="/css/style.css" rel="stylesheet">
</head>
<body class="d-flex">

  <?php require_once __DIR__ . '/sidebar.php'; ?>

  <main id="content" class="flex-grow-1 p-4">
    <div class="card mx-auto" style="max-width: 500px;">
      <div class="card-header text-center">Importar Productos</div>
      <div class="card-body">
        <?php if ($message): ?>
          <div class="alert alert-info"><?= $message ?></div>
        <?php endif; ?>
        <form method="post" enctype="multipart/form-data">
          <div class="mb-3">
            <label for="csv_file" class="form-label">Selecciona CSV</label>
            <input type="file" name="csv_file" id="csv_file" accept=".csv" class="form-control" required>
          </div>
          <button class="btn btn-primary w-100" type="submit">Importar Productos</button>
        </form>
      </div>
    </div>
  </main>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>