fetch( "SELECT * FROM message_templates WHERE id = ?", [$templateId] ); if (!$template) { throw new Exception('Plantilla no encontrada'); } // Obtener textos de la plantilla $bodyText = $template['body_text'] ?? ''; $headerText = $template['header_text'] ?? null; $footerText = $template['footer_text'] ?? null; // Obtener variables guardadas para saber sus placeholders $exampleParams = json_decode($template['example_parameters'] ?? '{}', true); $savedVariables = $exampleParams['variables'] ?? []; // Reemplazar variables en el body $bodyPreview = $bodyText; if (is_array($parameters)) { // Si tenemos variables guardadas, usar sus placeholders if (!empty($savedVariables)) { foreach ($savedVariables as $var) { $index = $var['index'] - 1; // Convertir a índice de array (0-based) if (isset($parameters[$index])) { $placeholder = $var['placeholder']; // Ejemplo: {{nombre_tema}} o {{1}} $bodyPreview = str_replace($placeholder, $parameters[$index], $bodyPreview); } } } else { // Fallback: reemplazar variables numéricas estándar foreach ($parameters as $index => $value) { $placeholder = '{{' . ($index + 1) . '}}'; $bodyPreview = str_replace($placeholder, $value, $bodyPreview); } } } // Reemplazar variables en el header si existen $headerPreview = $headerText; if ($headerText && is_array($parameters)) { if (!empty($savedVariables)) { foreach ($savedVariables as $var) { $index = $var['index'] - 1; if (isset($parameters[$index])) { $placeholder = $var['placeholder']; $headerPreview = str_replace($placeholder, $parameters[$index], $headerPreview); } } } else { foreach ($parameters as $index => $value) { $placeholder = '{{' . ($index + 1) . '}}'; $headerPreview = str_replace($placeholder, $value, $headerPreview); } } } // Verificar si quedan variables sin reemplazar (tanto numéricas como con nombres) $hasUnreplacedVars = preg_match('/\{\{[^\}]+\}\}/', $bodyPreview); // Generar vista previa HTML $htmlPreview = ''; if ($headerPreview) { $htmlPreview .= '
'; $htmlPreview .= htmlspecialchars($headerPreview); $htmlPreview .= '
'; } $htmlPreview .= '
'; $htmlPreview .= nl2br(htmlspecialchars($bodyPreview)); $htmlPreview .= '
'; if ($footerText) { $htmlPreview .= ''; } echo json_encode([ 'success' => true, 'preview' => [ 'body' => $bodyPreview, 'header' => $headerPreview, 'footer' => $footerText, 'html' => $htmlPreview, 'has_unreplaced_variables' => $hasUnreplacedVars, 'is_complete' => !$hasUnreplacedVars ] ], JSON_UNESCAPED_UNICODE); } catch (Exception $e) { error_log("Error in preview_template.php: " . $e->getMessage()); http_response_code(500); echo json_encode([ 'success' => false, 'error' => $e->getMessage() ]); }