<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');

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

try {
    // Usar conexión desde config
    $db = Database::getInstance();
    
    // Obtener todas las plantillas
    $stmt = $db->query("SELECT * FROM message_templates ORDER BY template_name");
    $templates = $stmt->fetchAll();
    
    $result = [
        'success' => true,
        'templates' => [],
        'summary' => [
            'total' => count($templates),
            'approved' => 0,
            'pending' => 0,
            'rejected' => 0
        ]
    ];
    
    foreach ($templates as $template) {
        $result['templates'][] = [
            'id' => $template['id'],
            'name' => $template['template_name'],
            'language' => $template['language_code'] ?: 'es',
            'status' => $template['status'] ?: 'pending',
            'category' => $template['category'] ?: 'UTILITY',
            'created' => $template['created_at'] ?: 'N/A'
        ];
        
        // Contar por estado
        $status = $template['status'] ?: 'pending';
        if (isset($result['summary'][$status])) {
            $result['summary'][$status]++;
        }
    }
    
    echo json_encode($result);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Error al verificar plantillas: ' . $e->getMessage()
    ]);
}
?>