<?php
class TicketTemplateController {

    // GET /ticket-templates — listar templates activos
    public static function index(): void {
        AuthMiddleware::verificar();
        $db = getDB();
        $stmt = $db->query("SELECT tt.*, c.nombre as categoria_nombre
            FROM ticket_templates tt 
            LEFT JOIN categorias c ON tt.categoria_id = c.id 
            WHERE tt.activo = 1 
            ORDER BY tt.orden ASC, tt.nombre ASC");
        Response::success($stmt->fetchAll());
    }

    // GET /ticket-templates/:id
    public static function ver(int $id): void {
        AuthMiddleware::verificar();
        $db = getDB();
        $stmt = $db->prepare("SELECT tt.*, c.nombre as categoria_nombre
            FROM ticket_templates tt 
            LEFT JOIN categorias c ON tt.categoria_id = c.id 
            WHERE tt.id = ?");
        $stmt->execute([$id]);
        $t = $stmt->fetch();
        if (!$t) Response::notFound('Template no encontrado');
        Response::success($t);
    }

    // POST /ticket-templates — crear
    public static function crear(): void {
        $payload = AuthMiddleware::verificar();
        RoleMiddleware::requireAdmin($payload);
        $db = getDB();
        $body = Validator::getBody();

        $stmt = $db->prepare("INSERT INTO ticket_templates (nombre, descripcion, categoria_id, subcategoria_id, prioridad, campos_extra, titulo_default, descripcion_default, icono, orden) VALUES (?,?,?,?,?,?,?,?,?,?)");
        $stmt->execute([
            $body['nombre'], $body['descripcion'] ?? null,
            $body['categoria_id'] ?? null, $body['subcategoria_id'] ?? null,
            $body['prioridad'] ?? 'media',
            isset($body['campos_extra']) ? json_encode($body['campos_extra']) : null,
            $body['titulo_default'] ?? null, $body['descripcion_default'] ?? null,
            $body['icono'] ?? 'clipboard', $body['orden'] ?? 0
        ]);
        Response::success(['id' => (int)$db->lastInsertId()], 'Template creado');
    }

    // PUT /ticket-templates/:id — editar
    public static function actualizar(int $id): void {
        $payload = AuthMiddleware::verificar();
        RoleMiddleware::requireAdmin($payload);
        $db = getDB();
        $body = Validator::getBody();

        $fields = []; $params = [];
        foreach (['nombre','descripcion','categoria_id','subcategoria_id','prioridad','titulo_default','descripcion_default','icono','orden','activo'] as $f) {
            if (array_key_exists($f, $body)) { $fields[] = "$f = ?"; $params[] = $body[$f]; }
        }
        if (isset($body['campos_extra'])) { $fields[] = "campos_extra = ?"; $params[] = json_encode($body['campos_extra']); }
        if (empty($fields)) Response::error('Nada que actualizar');

        $params[] = $id;
        $db->prepare("UPDATE ticket_templates SET " . implode(', ', $fields) . " WHERE id = ?")->execute($params);
        Response::success(null, 'Template actualizado');
    }

    // DELETE /ticket-templates/:id — desactivar
    public static function eliminar(int $id): void {
        $payload = AuthMiddleware::verificar();
        RoleMiddleware::requireAdmin($payload);
        $db = getDB();
        $db->prepare("UPDATE ticket_templates SET activo = 0 WHERE id = ?")->execute([$id]);
        Response::success(null, 'Template desactivado');
    }
}
