theloftstore/public/userarea/load_existing_mappings.php
2025-03-08 08:34:00 +01:00

61 lines
2.6 KiB
PHP
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
require_once(__DIR__ . '/class/db-functions.php');
header('Content-Type: application/json');
if (!isset($_GET['template_id']) || !is_numeric($_GET['template_id'])) {
echo json_encode(["success" => 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()]);
}