<?php
/**
 * API - Generar vista previa de plantilla con parámetros
 * Reemplaza las variables y muestra cómo se verá el mensaje final
 */

require_once '../config/config.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

requireAuthentication();

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Datos inválidos');
    }
    
    $templateId = $input['template_id'] ?? null;
    $parameters = $input['parameters'] ?? [];
    
    if (!$templateId) {
        throw new Exception('Se requiere ID de plantilla');
    }
    
    $db = Database::getInstance();
    $template = $db->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 .= '<div class="template-header" style="font-weight: bold; margin-bottom: 8px; color: #075e54;">';
        $htmlPreview .= htmlspecialchars($headerPreview);
        $htmlPreview .= '</div>';
    }
    
    $htmlPreview .= '<div class="template-body" style="margin-bottom: 8px;">';
    $htmlPreview .= nl2br(htmlspecialchars($bodyPreview));
    $htmlPreview .= '</div>';
    
    if ($footerText) {
        $htmlPreview .= '<div class="template-footer" style="font-size: 0.85em; color: #667781; margin-top: 8px;">';
        $htmlPreview .= htmlspecialchars($footerText);
        $htmlPreview .= '</div>';
    }
    
    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()
    ]);
}
