<?php
require_once __DIR__ . '/../../../config/bootstrap.php';
require_once __DIR__ . '/../../../includes/require-auth.php';

use App\Services\AuthService;
use App\Services\TemplateService;

header('Content-Type: application/json');

$auth = new AuthService();
$templateService = new TemplateService();

// Obtener usuario autenticado
$user = $auth->user();
if (!$user) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'No autenticado']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Método no permitido']);
    exit;
}

$templateId = (int)($_GET['id'] ?? 0);

if ($templateId <= 0) {
    echo json_encode(['success' => false, 'message' => 'ID de plantilla inválido']);
    exit;
}

try {
    $template = $templateService->getById($templateId);

    if (!$template) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Plantilla no encontrada']);
        exit;
    }

    if (!$template['activo']) {
        echo json_encode(['success' => false, 'message' => 'Esta plantilla no está disponible']);
        exit;
    }

    // Incrementar contador de uso
    $templateService->incrementUsage($templateId);

    echo json_encode([
        'success' => true,
        'template' => [
            'id' => $template['id'],
            'nombre' => $template['nombre'],
            'descripcion' => $template['descripcion'],
            'contenido' => $template['contenido'],
            'categoria' => $template['categoria']
        ]
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error al obtener la plantilla: ' . $e->getMessage()
    ]);
}
