false, "message" => "Invalid template ID"]); exit; } $template_id = intval($_GET['template_id']); try { $db = DBHandlerSelect::getInstance(); $pdo = $db->getConnection(); // 1️⃣ Recuperiamo il nome della tabella target da `excel_templates` $stmt = $pdo->prepare("SELECT target_table FROM excel_templates WHERE id = ?"); $stmt->execute([$template_id]); $template = $stmt->fetch(PDO::FETCH_ASSOC); if (!$template || empty($template['target_table'])) { echo json_encode(["success" => false, "message" => "Template not found or missing target table"]); exit; } $target_table = $template['target_table']; // 2️⃣ Recuperiamo le associazioni già esistenti per il template_id $stmt = $pdo->prepare("SELECT excel_column, mysql_column, headerexcel FROM excel_column_mappings WHERE template_id = ?"); $stmt->execute([$template_id]); $existing_mappings = $stmt->fetchAll(PDO::FETCH_ASSOC); // Creiamo gli array delle colonne già mappate $mapped_xls_columns = array_column($existing_mappings, 'excel_column'); $mapped_mysql_columns = array_column($existing_mappings, 'mysql_column'); // CORRETTO PER FILTRARE! // 3️⃣ Recuperiamo tutte le colonne disponibili nella tabella MySQL target $stmt = $pdo->prepare("SHOW COLUMNS FROM `$target_table`"); $stmt->execute(); $table_columns = $stmt->fetchAll(PDO::FETCH_COLUMN); // 🔥 FIX: Rimuoviamo le colonne MySQL che sono già state mappate! $remaining_mysql_columns = array_values(array_diff($table_columns, $mapped_mysql_columns)); // 4️⃣ Se abbiamo salvato gli header XLSX in `headerexcel`, li usiamo per calcolare le colonne XLSX non mappate $headerexcel = !empty($existing_mappings) ? $existing_mappings[0]['headerexcel'] : ''; $all_xls_columns = !empty($headerexcel) ? explode(',', $headerexcel) : []; $remaining_xls_columns = array_values(array_diff($all_xls_columns, $mapped_xls_columns)); // 5️⃣ Invio dei dati al frontend echo json_encode([ "success" => true, "mappings" => $existing_mappings, "remaining_xls_columns" => $remaining_xls_columns, "remaining_mysql_columns" => $remaining_mysql_columns // 🔥 ORA LE COLONNE MYSQL SONO FILTRATE! ]); } catch (PDOException $e) { echo json_encode(["success" => false, "message" => "Database error: " . $e->getMessage()]); }