$varIndex, 'placeholder' => "{{" . $varName . "}}", 'name' => $varName, 'example' => $example ]; } error_log("✅ Variables procesadas para '{$templateName}': " . json_encode($variables, JSON_UNESCAPED_UNICODE)); } } // Si encontramos variables, agregarlas a example_parameters if (!empty($variables)) { $exampleParameters['variables'] = $variables; error_log("💾 example_parameters final para '{$templateName}': " . json_encode($exampleParameters, JSON_UNESCAPED_UNICODE)); } // Preparar datos para guardar $componentsJson = !empty($components) ? json_encode($components, JSON_UNESCAPED_UNICODE) : null; $exampleJson = !empty($exampleParameters) ? json_encode($exampleParameters, JSON_UNESCAPED_UNICODE) : null; // Verificar si la plantilla ya existe $existing = $db->fetch( "SELECT id, status FROM message_templates WHERE template_name = ? AND language_code = ?", [$templateName, $language] ); if ($existing) { // Actualizar plantilla existente con nuevos campos $db->execute( "UPDATE message_templates SET status = ?, category = ?, body_text = ?, header_text = ?, header_type = ?, footer_text = ?, components = ?, example_parameters = ?, updated_at = NOW() WHERE id = ?", [ strtolower($status), strtolower($category), $bodyText, $headerText, $headerType, $footerText, $componentsJson, $exampleJson, $existing['id'] ] ); $updatedCount++; } else { // Insertar nueva plantilla con componentes $db->execute( "INSERT INTO message_templates ( name, template_name, language_code, category, status, body_text, header_text, header_type, footer_text, components, example_parameters, created_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())", [ $templateName, // nombre descriptivo igual al nombre técnico $templateName, $language, strtolower($category), strtolower($status), $bodyText, $headerText, $headerType, $footerText, $componentsJson, $exampleJson ] ); $syncedCount++; } } catch (Exception $e) { $errors[] = "Error procesando plantilla '{$templateName}': " . $e->getMessage(); } } // Log de la sincronización writeLog('INFO', "Plantillas sincronizadas desde Facebook: {$syncedCount} nuevas, {$updatedCount} actualizadas, {$skippedCount} sin cambios"); echo json_encode([ 'success' => true, 'message' => 'Plantillas sincronizadas correctamente', 'data' => [ 'total' => count($templates), 'synced' => $syncedCount, 'updated' => $updatedCount, 'skipped' => $skippedCount, 'errors' => $errors ] ]); } catch (Exception $e) { error_log("Error in sync_templates_from_facebook.php: " . $e->getMessage()); http_response_code(500); echo json_encode([ 'success' => false, 'error' => $e->getMessage() ]); }