PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]; try { $pdo = new PDO($dsn, $user, $pass, $options); // Verificar si se ha pasado un archivo por GET if (!isset($_GET['file'])) { throw new Exception("❌ Debes especificar el archivo JSON con ?file=nombre.json"); } $filename = basename($_GET['file']); // protección básica $filepath = __DIR__ . '/' . $filename; if (!file_exists($filepath)) { throw new Exception("❌ El archivo $filename no existe"); } $jsonData = file_get_contents($filepath); $data = json_decode($jsonData, true); if (!$data) { throw new Exception("❌ El archivo JSON no es válido"); } // Insertar ticket $stmt = $pdo->prepare("INSERT INTO tickets (tienda_id, fecha, total, metodo_pago) VALUES (?, ?, ?, ?)"); $stmt->execute([ $data['tienda_id'], $data['fecha'], $data['total'], $data['metodo_pago'] ]); $ticket_id = $pdo->lastInsertId(); foreach ($data['productos'] as $p) { // Verificar si el producto ya existe $stmt = $pdo->prepare("SELECT id FROM productos WHERE codigo_barras = ?"); $stmt->execute([$p['codigo_barras']]); $producto = $stmt->fetch(); if ($producto) { $producto_id = $producto['id']; } else { // Insertar nuevo producto $stmt = $pdo->prepare("INSERT INTO productos (nombre, marca_id, codigo_barras) VALUES (?, ?, ?)"); $stmt->execute([ $p['nombre'], $p['marca_id'], $p['codigo_barras'] ]); $producto_id = $pdo->lastInsertId(); } // Insertar línea del ticket $stmt = $pdo->prepare("INSERT INTO lineas_ticket (ticket_id, producto_id, cantidad, precio_unitario) VALUES (?, ?, ?, ?)"); $stmt->execute([ $ticket_id, $producto_id, $p['cantidad'], $p['precio'] ]); } echo "✅ Ticket insertado correctamente con ID $ticket_id"; } catch (Exception $e) { echo "❌ Error: " . $e->getMessage(); }