getConnection(); // Get default idclient from template $stmt = $pdo->prepare("SELECT idclient FROM excel_templates WHERE id = ?"); $stmt->execute([$templateId]); $template = $stmt->fetch(PDO::FETCH_ASSOC); $idclient = $template['idclient'] ?? null; // Use provided importreferencecode (from filtered page) or generate new $importReferenceCode = $importRefFromClient !== '' ? $importRefFromClient : date('YmdHis') . '-' . uniqid(); // Insert empty record $stmt = $pdo->prepare(" INSERT INTO datadb (templateid, user_id, status, idclient, importreferencecode, importdate) VALUES (?, ?, 'i', ?, ?, NOW()) "); $stmt->execute([$templateId, $userId, $idclient, $importReferenceCode]); $iddatadb = (int)$pdo->lastInsertId(); // Create import_data_details for all mappings (with auto_value support) $mappingStmt = $pdo->prepare("SELECT id, auto_value, manual_default, data_type FROM template_mapping WHERE template_id = ?"); $mappingStmt->execute([$templateId]); $mappings = $mappingStmt->fetchAll(PDO::FETCH_ASSOC); if (!empty($mappings)) { $insertStmt = $pdo->prepare("INSERT INTO import_data_details (id, mapping_id, field_value) VALUES (?, ?, ?)"); foreach ($mappings as $m) { $val = ''; $auto = $m['auto_value'] ?? 'none'; if ($auto === 'import_date') { $val = date('Y-m-d'); } elseif ($auto === 'import_time') { $val = date('H:i'); } elseif ($m['data_type'] === 'DATE' && ($m['manual_default'] ?? '') === 'today') { $val = date('Y-m-d'); } elseif (!empty($m['manual_default'])) { $val = $m['manual_default']; } $insertStmt->execute([$iddatadb, $m['id'], $val]); } } // Get user name $userStmt = $pdo->prepare("SELECT CONCAT(first_name, ' ', last_name) AS user_name FROM auth_users WHERE id = ?"); $userStmt->execute([$userId]); $userName = $userStmt->fetchColumn() ?: ''; echo json_encode([ 'success' => true, 'iddatadb' => $iddatadb, 'importreferencecode' => $importReferenceCode, 'user_name' => $userName, ]); } catch (Exception $e) { http_response_code(500); echo json_encode(['success' => false, 'message' => $e->getMessage()]); }