<?php
/**
 * API - Obtener detalles completos de una plantilla con variables
 * Devuelve los parámetros que se deben llenar
 */

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

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

requireAuthentication();

try {
    $templateId = isset($_GET['id']) ? intval($_GET['id']) : null;
    $templateName = isset($_GET['name']) ? trim($_GET['name']) : null;
    $language = isset($_GET['language']) ? trim($_GET['language']) : 'es';
    
    if (!$templateId && !$templateName) {
        throw new Exception('Se requiere ID o nombre de plantilla');
    }
    
    $db = Database::getInstance();
    
    if ($templateId) {
        $template = $db->fetch(
            "SELECT * FROM message_templates WHERE id = ?",
            [$templateId]
        );
    } else {
        $template = $db->fetch(
            "SELECT * FROM message_templates WHERE template_name = ? AND language_code = ?",
            [$templateName, $language]
        );
    }
    
    if (!$template) {
        throw new Exception('Plantilla no encontrada');
    }
    
    // Extraer variables del body_text o de example_parameters
    $bodyText = $template['body_text'] ?? '';
    $variables = [];
    
    // Primero intentar usar las variables guardadas en example_parameters
    if (!empty($template['example_parameters'])) {
        $examples = json_decode($template['example_parameters'], true);
        if (isset($examples['variables']) && is_array($examples['variables'])) {
            // Usar las variables ya procesadas durante la sincronización
            foreach ($examples['variables'] as $var) {
                $varName = $var['name'] ?? $var['index'];
                $variables[] = [
                    'index' => $var['index'],
                    'placeholder' => $var['placeholder'],
                    'label' => is_numeric($varName) ? 'Variable ' . $varName : ucfirst(str_replace('_', ' ', $varName)),
                    'required' => true,
                    'example' => $var['example'] ?? null
                ];
            }
        }
    }
    
    // Si no hay variables guardadas, extraerlas del body_text (fallback)
    if (empty($variables) && preg_match_all('/\{\{([^\}]+)\}\}/', $bodyText, $matches)) {
        $uniqueVars = array_unique($matches[1]);
        
        $index = 1;
        foreach ($uniqueVars as $varName) {
            $varIndex = is_numeric($varName) ? intval($varName) : $index++;
            $variables[] = [
                'index' => $varIndex,
                'placeholder' => '{{' . $varName . '}}',
                'label' => is_numeric($varName) ? 'Variable ' . $varName : ucfirst(str_replace('_', ' ', $varName)),
                'required' => true,
                'example' => null
            ];
        }
    }
    
    // Preparar respuesta
    $response = [
        'success' => true,
        'template' => [
            'id' => $template['id'],
            'name' => $template['name'],
            'template_name' => $template['template_name'],
            'language_code' => $template['language_code'],
            'category' => $template['category'],
            'status' => $template['status'],
            'body_text' => $bodyText,
            'header_text' => $template['header_text'] ?? null,
            'header_type' => $template['header_type'] ?? null,
            'footer_text' => $template['footer_text'] ?? null,
            'has_variables' => count($variables) > 0,
            'variables_count' => count($variables),
            'variables' => $variables
        ]
    ];
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    
} catch (Exception $e) {
    error_log("Error in get_template_details.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
