<?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 editar 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;
}

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

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

$data = [];

if (isset($_POST['nombre'])) {
    $data['nombre'] = $_POST['nombre'];
}

if (isset($_POST['descripcion'])) {
    $data['descripcion'] = $_POST['descripcion'];
}

if (isset($_POST['contenido'])) {
    $data['contenido'] = $_POST['contenido'];
}

if (isset($_POST['categoria'])) {
    $data['categoria'] = $_POST['categoria'];
}

if (isset($_POST['activo'])) {
    $data['activo'] = (int)$_POST['activo'];
}

$result = $templateService->update($templateId, $data);

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