<?php
/**
 * API - Obtener plantillas de mensaje
 * Fecha: 13 de noviembre de 2025
 */

session_start();
require_once '../config/config.php';

// Suprimir errores para obtener JSON limpio
error_reporting(E_ERROR | E_PARSE);

// Modo debug: desactivar autenticación si existe el parámetro debug
$debugMode = isset($_GET['debug']) && $_GET['debug'] === 'true';

if (!$debugMode) {
    requireAuthentication();
}

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');

try {
    $db = Database::getInstance();
    
    $approvedOnly = isset($_GET['approved_only']) && $_GET['approved_only'] == '1';
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : null;

    // Incluir todos los campos necesarios para la UI
    $sql = "SELECT 
                id, 
                name, 
                template_name, 
                language_code, 
                category, 
                status, 
                body_text,
                header_text,
                header_type,
                footer_text,
                components,
                example_parameters,
                created_at 
            FROM message_templates";
    $params = [];

    if ($approvedOnly) {
        $sql .= " WHERE status = 'approved'";
    }

    $sql .= " ORDER BY name ASC";

    if ($limit && $limit > 0) {
        $sql .= " LIMIT " . $limit;
    }

    $templates = $db->fetchAll($sql, $params);
    
    echo json_encode([
        'success' => true,
        'data' => $templates
    ]);
    
} catch (Exception $e) {
    error_log("Error in get_templates.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Error interno del servidor'
    ]);
}
?>