<?php
class CategoriaController {
    public static function index(): void {
        AuthMiddleware::verificar();
        $db = getDB();
        $stmt = $db->query("SELECT c.*, (SELECT COUNT(*) FROM tickets t WHERE t.categoria_id = c.id) as total_tickets FROM categorias c ORDER BY c.orden, c.nombre");
        $categorias = $stmt->fetchAll();

        // Attach subcategorias to each category
        try {
            $subStmt = $db->query("SELECT * FROM subcategorias ORDER BY orden, nombre");
            $subs = $subStmt->fetchAll();
            foreach ($categorias as &$cat) {
                $cat['subcategorias'] = array_values(array_filter($subs, fn($s) => (int)$s['categoria_id'] === (int)$cat['id']));
            }
        } catch (\Exception $e) {
            // subcategorias table may not exist yet
            foreach ($categorias as &$cat) { $cat['subcategorias'] = []; }
        }
        Response::success($categorias);
    }

    public static function crear(): void {
        $payload = AuthMiddleware::verificar();
        RoleMiddleware::requireTecnico($payload);
        $body = Validator::getBody();
        Validator::make($body)->required('nombre')->validate();
        $db = getDB();
        $orden = (int)$db->query("SELECT COALESCE(MAX(orden),0)+1 FROM categorias")->fetchColumn();
        $stmt = $db->prepare("INSERT INTO categorias (nombre, descripcion, color, icono, sla_horas, orden) VALUES (?,?,?,?,?,?)");
        $stmt->execute([$body['nombre'], $body['descripcion'] ?? null, $body['color'] ?? '#3b82f6', $body['icono'] ?? 'tag', (int)($body['sla_horas'] ?? 24), $orden]);
        $id = (int)$db->lastInsertId();
        if (class_exists('AuditService')) AuditService::categoriaCreada($id);
        Response::created(['id' => $id]);
    }

    public static function actualizar(int $id): void {
        $payload = AuthMiddleware::verificar();
        RoleMiddleware::requireTecnico($payload);
        $body = Validator::getBody();
        $db = getDB();
        $fields = []; $params = [];
        foreach (['nombre','descripcion','color','icono','sla_horas','activa','orden'] as $f) {
            if (array_key_exists($f, $body)) { $fields[] = "$f = ?"; $params[] = $body[$f]; }
        }
        if (empty($fields)) Response::error('Nada que actualizar');
        $params[] = $id;
        $db->prepare("UPDATE categorias SET " . implode(', ', $fields) . " WHERE id = ?")->execute($params);
        Response::success(null, 'Categoría actualizada');
    }

    public static function eliminar(int $id): void {
        $payload = AuthMiddleware::verificar();
        RoleMiddleware::requireTecnico($payload);
        $db = getDB();
        $stmt = $db->prepare("SELECT COUNT(*) FROM tickets WHERE categoria_id = ?");
        $stmt->execute([$id]);
        if ((int)$stmt->fetchColumn() > 0) {
            Response::error('No se puede eliminar: tiene tickets asociados. Desactívala en su lugar.');
        }
        $db->prepare("DELETE FROM categorias WHERE id = ?")->execute([$id]);
        Response::success(null, 'Categoría eliminada');
    }

    // ---- SUBCATEGORÍAS ----

    public static function crearSub(): void {
        $payload = AuthMiddleware::verificar();
        RoleMiddleware::requireTecnico($payload);
        $body = Validator::getBody();
        Validator::make($body)->required('nombre', 'categoria_id')->validate();
        $db = getDB();
        $stmt = $db->prepare("INSERT INTO subcategorias (categoria_id, nombre, descripcion, orden) VALUES (?,?,?,?)");
        $orden = (int)$db->query("SELECT COALESCE(MAX(orden),0)+1 FROM subcategorias WHERE categoria_id = " . (int)$body['categoria_id'])->fetchColumn();
        $stmt->execute([(int)$body['categoria_id'], $body['nombre'], $body['descripcion'] ?? null, $orden]);
        Response::created(['id' => (int)$db->lastInsertId()]);
    }

    public static function actualizarSub(int $id): void {
        $payload = AuthMiddleware::verificar();
        RoleMiddleware::requireTecnico($payload);
        $body = Validator::getBody();
        $db = getDB();
        $fields = []; $params = [];
        foreach (['nombre','descripcion','activa','orden'] as $f) {
            if (array_key_exists($f, $body)) { $fields[] = "$f = ?"; $params[] = $body[$f]; }
        }
        if (empty($fields)) Response::error('Nada que actualizar');
        $params[] = $id;
        $db->prepare("UPDATE subcategorias SET " . implode(', ', $fields) . " WHERE id = ?")->execute($params);
        Response::success(null, 'Subcategoría actualizada');
    }

    public static function eliminarSub(int $id): void {
        $payload = AuthMiddleware::verificar();
        RoleMiddleware::requireTecnico($payload);
        $db = getDB();
        $db->prepare("DELETE FROM subcategorias WHERE id = ?")->execute([$id]);
        Response::success(null, 'Subcategoría eliminada');
    }

    public static function subsPorCategoria(int $catId): void {
        AuthMiddleware::verificar();
        $db = getDB();
        $stmt = $db->prepare("SELECT * FROM subcategorias WHERE categoria_id = ? AND activa = 1 ORDER BY orden, nombre");
        $stmt->execute([$catId]);
        Response::success($stmt->fetchAll());
    }
}