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

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

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

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

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

// ✅ Asesores y administradores pueden crear plantillas
// No requiere verificación adicional de rol

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

// Verificar CSRF token
if (!$security->verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Token de seguridad inválido']);
    exit;
}

$data = [
    'nombre' => $_POST['nombre'] ?? '',
    'descripcion' => $_POST['descripcion'] ?? '',
    'contenido' => $_POST['contenido'] ?? '',
    'categoria' => $_POST['categoria'] ?? 'general'
];

$result = $templateService->create($data);

http_response_code($result['success'] ? 200 : 400);
echo json_encode($result);
